问题描述
我在ES6类中有多个嵌套函数。现在,我想知道如何轻松地将类实例的 this 绑定到所有子功能。
我知道...
subfunction1.bind(this)();
...但是对于多个嵌套函数来说,这似乎是一个尴尬的解决方案。
有人知道更优雅的解决方案吗?
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();
解决方法
您可以使用箭头功能。它们以类似的方式工作。 箭头符号会将其替换为箭头函数作用域的上下文值。
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();
,
声明一个将在子函数范围内的局部变量,并使用它代替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();