关于 javascript 中 this 参数的问题

2018-07-23 17:48:54 +08:00
 jinxinking007

var obj={ birth:1995, getAge:function(year){ var that=this; function getAge(){ return new Date().getFullYear()-that.birth; } return getAge(); } }; var obj3={ birth:1997, getAge:function(){ return year=>year-this.birth; } }; var obj2={ birth:1996, getAge:()=>(y=>this.birth), }; console.log(obj.getAge(2018)); console.log(obj3.getAge()(2018)); console.log(obj2.getAge()(2018));

输出结果为: 23 21 undefined

第一种使用了一种 hack 方法规避了 this 的 bug,二三两种用的都是箭头函数,为什么二可行,而三不可行呢?

2762 次点击
所在节点    JavaScript
5 条回复
jinxinking007
2018-07-23 17:52:19 +08:00
这排版可读性太低,提取关键部分就是 getAge:function(){ return year=>year-this.birth; }和 getAge:()=>(y=>this.birth),两者的区别
ysc3839
2018-07-23 17:57:46 +08:00
guomuzz
2018-07-23 19:24:22 +08:00
var obj3 = {
birth: 1997,
getAge: function () {
console.log(this)
return year => year - this.birth;
}
};
var obj2 = {
birth: 1996,
getAge: () => {
console.log(this)
return y => this.birth
},
};

打印一下就知道了
DrugsZ
2018-07-24 09:17:55 +08:00
箭头函数的 this 是在函数创建的时候就锁定了不能更改了的,就算用 call,apply,bind 也不行会报错
zhzer
2018-07-24 11:06:40 +08:00
在 js 里的 json 对象,只是一层面向对象语法糖,相对来说不是特别严谨,箭头函数无法手动设定 this 也就无法适用这层修饰

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/473402

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX