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,二三两种用的都是箭头函数,为什么二可行,而三不可行呢?