距开课0天0时0分-10140998秒
小葫芦2016-11-09 11:36:21 0 2 355
[JavaScript讨论组]举报回复话题 ↕
var person = { name: "Nicholas", sayName() { console.log(this.name); } }; var person = { name: "Nicholas", sayName:()=> { console.log(this.name); } };
这两种写法有什么区别?
2
0
分享
代言 2016-11-09 11:37:052楼
this的不一样,箭头函数不会产生新的this
赞 +0添加回复
三叔 2016-11-09 11:36:491楼
区别在于第一个 this 指向 person,也就是你调用 person.sayName() 时可以得到 Nicholas,第二个实际上可以看作
var person = { name: "Nicholas", sayName: function() { console.log(this.name); } };
它的 this 实际上指向的是 window 而不是 person,所以取不到对应的 name 值
代言 2016-11-09 11:37:052楼
this的不一样,箭头函数不会产生新的this
赞 +0添加回复
三叔 2016-11-09 11:36:491楼
区别在于第一个 this 指向 person,也就是你调用 person.sayName() 时可以得到 Nicholas,第二个实际上可以看作
它的 this 实际上指向的是 window 而不是 person,所以取不到对应的 name 值
赞 +0添加回复