es中的关于this指针丢失问题
 发布于 7 年前  作者 linxiaoziruo  3338 次预览  最后一次回复是 7 年前  来自 问答 

let a = { name: ‘zaki’, say: function() { console.log(this); console.log(this.name); } };

(function() { a.say(); //可以打印出符合期望的的this信息 let fn = a.say; fn(); // 不能打印出符合期望的this信息 })()

6 回复
justjavac

搜索 “js this” 你就找到答案了

justjavac

js 最难(坑)的就是 this

linxiaoziruo

感谢各位的回答,现在已经完全弄清楚了!

pretty-foam

赋值a.say函数没执行就是一个匿名函数,匿名函数的this指向全局。我这样理解对不对?

972389149

class里的方法的this指向的是实例,你可以在构造函数里绑定一下this的指向 class = { constructor (){ this.say = this.say,bind(this); } }