简洁度
- 将原函数的“function”关键字和函数名都删掉,并使用“=>”连接参数列表和函数体
# 通用函数
var fn1 = function(a, b) {
return a + b
}
function fn2(a, b) {
return a + b
}
#=>函数
var fn1 = (a, b) => {
return a + b
}
(a, b) => {
return a + b
}
- 当函数参数只有一个,括号可以省略;但是没有参数时,括号不可以省略。
// 无参
var fn1 = function() {}
var fn1 = () => {}
// 单个参数
var fn2 = function(a) {}
var fn2 = a => {}
// 多个参数
var fn3 = function(a, b) {}
var fn3 = (a, b) => {}
// 可变参数
var fn4 = function(a, b, ...args) {}
var fn4 = (a, b, ...args) => {}
- 箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种只包含一个表达式,省略掉了{ … }和return。还有一种可以包含多条语句,这时候就不能省略{ … }和return
() => return 'hello'
(a, b) => a + b
(a) => {
a = a + 1
return a
}
如果返回一个对象,需要特别注意,如果是单表达式要返回自定义对象,不写括号会报错,因为和函数体的{ … }有语法冲突。
注意,用小括号包含大括号则是对象的定义,而非函数主体
x => {key: x} // 报错
x => ({key: x}) // 正确
this指向
箭头函数内部的this是词法作用域,由上下文确定,词法作用域是由你在写代码时将变量和块作用域写在哪里来决定的。
var name = 'monkey';
var obj = {
name : 'John',
getName : function(){
console.log(this.name);
var other = function () {
console.log(this.name);
}
other();
}
};
obj.getName();
// 结果
// John
// monkey
var name = 'monkey';
var obj = {
name : 'John',
getName : function(){
console.log(this.name);
var other = () => console.log(this.name);
other();
}
};
obj.getName();
// John
// John
4.箭头函数无法使用 call()或 apply()来改变其运行的作用域。
var name = 'monkey';
var obj = {
name : 'John',
name2: 'Tom',
getName : function(name){
console.log(this.name)
var other = function () {
console.log(this.name)
console.log(name + this.name + this.name2);
}
other.call({name: 'jason'}, name);
}
};
obj.getName('hi');
// 结果
// John
// jason
// hijasonundefined
var name = 'monkey';
var obj = {
name : 'John',
name2: 'Tom',
getName : function(name){
console.log(this.name)
var other = () => {
console.log(this.name)
console.log(name + this.name + this.name2);
}
other.call({name: 'jason'}, name);
}
};
obj.getName('hi');
// 结果
// John
// John
// hiJohnTom
使用箭头函数之后,不再需要以前hack的写法,var that = this。
其他
- 箭头函数不能用于构造函数(不可以对箭头函数使用new命令)
var ful=function(age){
this.age=age;
}
var chl=new ful(18);
console.log(chl.age);//18
var ful = age => {
this.age=age;
}
var chl=new ful(18);//ful is not a constructor
console.log(chl.age);
- 箭头函数没有prototype属性
var fn = () => {};
console.log(fn.prototype); // undefined
- 箭头函数不绑定arguments(没有自己的 arguments,是父函数的arguments,如果没有父函数,则报错参数)
var arguments = 42;
var fn = () => arguments;
console.log(fn()); // 42
function foo() {
var f = (i) => arguments[0]+i;
return f(2);
}
console.log(foo(1)); // 3
总结
- 类似于匿名函数,在某些情况下使用,可减少代码量
- 代码简洁,this提前定义,代码太过简洁,导致不好阅读
- 箭头函数中没有this 的指向,在箭头函数中this 的指向会指向离他最近的那个作用域