class MyClass{
constructor(){
this.name="NAME";
}
callback(){
console.log(this.name);
}
do(){
this.callback(); //正常方法调用
let doback = this.callback.bind(this);
doback(); //也是可以的
setTimeout(()=>{
doback(); //可以的
console.log("In function " + this.name); //没问题
},10);
doback = this.callback;
doback(); //错误! 赋值导致this上下文丢失
}
}
let obj = new MyClass();
obj.do();
What‘s this in a class method and in a callback function?
最新推荐文章于 2024-08-14 15:45:18 发布