use*_*772 0 javascript oop function node.js
我有这种情况
class A {
a(params) {
//some code here
}
b(params) {
//some code here
}
c(params) {
this.a(function(data) {
console.log(this); // undefined
this.b(); // error no function b of undefined
})
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试将 this 绑定到 'a' using,bind(this)但它说无法读取未定义的属性 'bind' 或 this 未定义。当我打印这个时,我得到了 A 类。我想在“a”函数中调用它。
当你定义了一个 new 时function,里面的 的含义this已经改变了。您要么需要使用箭头函数:
this.a((data) => {
console.log(this); // class A
this.b();
})
Run Code Online (Sandbox Code Playgroud)
或将 的引用保存this在局部变量中:
var self = this;
this.a(function(data){
console.log(self); // class A
self.b();
})
Run Code Online (Sandbox Code Playgroud)