es中的关于this指针丢失问题
发布于 5 年前 作者 linxiaoziruo 2851 次浏览 来自 问答

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

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

6 回复

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

js 最难(坑)的就是 this

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

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

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

回到顶部