箭头函数可使咱们的代码更加简洁,以下:数组
var sum = (a,b) => a+b;
JavaScript 充满了咱们须要编写在其余地方执行的小函数的状况。app
例如:函数
……还有更多。this
JavaScript 的精髓在于建立一个函数并将其传递到某个地方。 在这样的函数中,咱们一般不想离开当前上下文。这就是箭头函数的主战场啦。spa
箭头函数没有 this 。若是访问 this ,则会从外 部获取。code
const group = { title: "Our Group", students: ["John", "Pete", "Alice"], showList() { this.students.forEach((student) => console.log(`${this.title}:${student}`)); }, }; group.showList();
如何使用普通函数则会出现错误,缘由以下:blog
this指向错误,由于函数调用的上下文并不是是group继承
⚠ 不能对箭头函数进行 new 操做 不具备 this 天然也就意味着另外一个限制:箭头函数不能用做构造器(constructor)。不能用 new 调用它们。教程
—《现代JavaScript教程》ip
箭头函数没有 “arguments”
当咱们须要使用当前的 this 和 arguments 转发一个调用时,这对装饰器(decorators)来讲 很是有用
function defer(f,ms) { return function () { setTimeout(()=>f.apply(this,arguments),ms); } } function sayHi(who) { console.log(`Hello ${who}`); } const sayHiDeferred = defer(sayHi,2000); sayHiDeferred('Peng');
如何使用普通函数的话,则须要以下这样:
function defer (f,ms) { return function(...args) { const ctx = this; setTimeout(function() { return f.apply(ctx,args); },ms); } }
箭头函数总结: