简单用法
箭头函数是函数表达式的写法。
之前的函数表达式
var foo = function (a, b) {return a + b};
使用箭头函数
var foo = (a, b) => {return a + b};
还可以更简单
var foo = (a, b) => a+ b;
一个参数还可以更省
var foo = a => a;
箭头函数带来什么好处?
- 书写更加的方便了,我们可以直接从书写形式上看出来
function foo(a) {
return function (b) {
return a + b;
}
}
用箭头函数书写
var foo = a => b => a + b;
- 函数都是有 this 的,但是有箭头函数没有自己的 this,箭头函数的 this 是引用的函数外的词法作用域的 this 指向。
setTimeout(function () {
console.log(this);
}, 1000);
setTimeout(() => {
console.log(this);
}, 1000);
这两个 this 都是指向了 window,但是指向 this 的过程是不一样的。
第一种是在 setTimeout 中进行调用。它的 this 是函数自身默认调用 this 绑定到了 window。
第二种是在 setTimeout 中调用,函数没有自身的 this,所以它找的是 setTimeout 的 this用的。
- 箭头函数不能被 new。正式因为没有 this ,所以不能被 new。
- 箭头函数没有 arguments 。所以箭头函数只能使用 rest 参数。
- 箭头函数也没有 super()
怎么用呢?
箭头函数没有自己的上下嗯,但是在当前上下文中起作用的短代码的。
当我们使用当前 this 和 arguments 转发一个调用时,对于一个装饰器来说非常有用。
function defer(func, ms) {
return function () {
setTimeout(() => func.apply(this, argument), ms);
}
}