箭头函数
x => x * x
相当于function (x) { return x * x; }
1 var obj = { 2 birth: 1990, 3 getAge: function () { 4 var b = this.birth; // 1990 5 var fn = function () { 6 return new Date().getFullYear() - this.birth; // this指向window或undefined 7 }; 8 return fn(); 9 } 10 };
//由于JavaScript函数对this
绑定的错误处理,上面的例子无法得到预期结果:
1 var obj = { 2 birth: 1990, 3 getAge: function () { 4 var b = this.birth; // 1990 5 var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象 6 return fn(); 7 } 8 }; 9 obj.getAge(); // 26