I have code like this:
mycode.js:
export default {
foo() {
return "foo";
},
bar() {
return "bar" + this.foo();
}
}
othercode.js:
import mycode from "mycode.js";
mycode.bar(); // usually works fine, returns "barfoo"
I'm having difficulty, though, calling mycode.bar() inside an arrow function. The problem is that "this" within bar() no longer refers to the object in mycode, it refers to the caller's context.
If I want to continue to use this code style for defining functions and exporting them, how do I call foo() within bar()?
I have tried to bind() the methods in mycode to the exported object, but so far as I can tell, you have to do that for each method individually.
I also tried to do this at the top of mycode:
let self = this;
and then refer to "self.foo()", but "this" isn't defined at the time I assign it to self.
I could totally change the code style. I could define each function like this:
mycode.js
function foo() {
return "foo";
}
export default {
foo, bar, ...
}
but then I have to name each function individually.
There's got to be a better way.