1.箭头函数定义:箭头函数允许我们编写更短的函数
2.例子 (引用w3School)
正常函数:
hello = function() {
return "Hello World!";
}
正常函数:
hello = () => {
return "Hello World!";
}
如果函数只有一个语句,并且该语句返回一个值,则可以去掉括号和 return 关键字:
hello = () => "Hello World!";
带参数:
hello = (val) => "Hello " + val;
只有一个参数时,也可以:
hello = val => "Hello " + val;
3.箭头函数的 this
箭头函数没有对 this 的绑定,
this 关键字始终表示定义箭头函数的对象:
两个例子:
1.正常函数
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = function () {
return new Date().getFullYear() - this.birth; // this指向window或undefined
};
return fn();
}
};
2.箭头函数:
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
return fn();
}
};
obj.getAge(); // 25
使用箭头函数,以前的那种:var that = this就不再需要了