【发布时间】:2020-08-14 18:28:05
【问题描述】:
我在一个 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();
【问题讨论】:
标签: javascript class ecmascript-6 this