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…
JavaScript
x
2
1
subfunction1.bind(this)();
2
…but it feels like an awkward solution for multiple nested functions.
Does anyone know of a more elegant solution?
JavaScript
1
26
26
1
class User {
2
constructor(name) {
3
this.name = name;
4
}
5
6
mainFunction() {
7
console.log(this.name);//"Paul"
8
9
//In order for the nested functions to get "this" it is needed to bind it
10
//to the subfunction as shown below. Is there an easier way to achieve
11
//this for all the subfunctions at once?
12
13
subfunction1.bind(this)();
14
subfunction2.bind(this)();
15
16
function subfunction1() {
17
console.log(this.name);//"Paul"
18
}
19
20
function subfunction2() {
21
console.log(this.name);//"Paul"
22
}
23
}
24
}
25
const paul = new User("Paul");
26
paul.mainFunction();
Advertisement
Answer
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.
JavaScript
1
19
19
1
class User {
2
constructor(name) {
3
this.name = name;
4
}
5
6
getSummary() {
7
console.log(this.name);
8
const subfunction1 = () => {
9
console.log(this.name);//"Paul"
10
}
11
const subfunction2 = () => {
12
console.log(this.name);//"Paul"
13
}
14
subfunction1();
15
subfunction2();
16
}
17
}
18
const paul = new User("Paul");
19
paul.getSummary();