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?
最新推荐文章于 2026-06-20 22:27:38 发布
文章讨论了JavaScript类中的`this`指向问题,介绍了构造函数中`this`的使用,以及如何通过`bind`保持在对象上下文中执行回调函数。特别强调了当将`callback`赋值给变量时,可能会导致`this`上下文丢失。

375

被折叠的 条评论
为什么被折叠?



