Reputation: 396
I have multiple nested functions in a ES6 Class. Now I wonder how I can easily bind this of the class instance to all the subfunctions.
I know of...
subfunction1.bind(this)();
...but it feels like an awkward solution for multiple nested functions.
Does anyone know of a more elegant solution?
class User {
constructor(name) {
this.name = name;
}
mainFunction() {
console.log(this.name);//"Paul"
//In order for the nested functions to get "this" it is needed to bind it
//to the subfunction as shown below. Is there an easier way to achieve
//this for all the subfunctions at once?
subfunction1.bind(this)();
subfunction2.bind(this)();
function subfunction1() {
console.log(this.name);//"Paul"
}
function subfunction2() {
console.log(this.name);//"Paul"
}
}
}
const paul = new User("Paul");
paul.mainFunction();
Upvotes: 0
Views: 801
Reputation: 556
You can use arrow functions. They work in rather a similar manner. The arrow notation will replace this with the value of the context of the arrow function's scope.
class User {
constructor(name) {
this.name = name;
}
getSummary() {
console.log(this.name);
const subfunction1 = () => {
console.log(this.name);//"Paul"
}
const subfunction2 = () => {
console.log(this.name);//"Paul"
}
subfunction1();
subfunction2();
}
}
const paul = new User("Paul");
paul.getSummary();
Upvotes: 4
Reputation: 780974
Declare a local variable that will be in the subfunctions' scope, and use that instead of this
.
class User {
constructor(name) {
this.name = name;
}
mainFunction() {
const self = this;
console.log(this.name);//"Paul"
subfunction1();
subfunction2();
function subfunction1() {
console.log(self.name);//"Paul"
}
function subfunction2() {
console.log(self.name);//"Paul"
}
}
}
const paul = new User("Paul");
paul.mainFunction();
Upvotes: 2