深刻理解JavaScript中的箭头

箭头函数可使咱们的代码更加简洁,以下:数组

var sum = (a,b) => a+b;

JavaScript 充满了咱们须要编写在其余地方执行的小函数的状况。app

例如:函数

  • arr.forEach(func) —— forEach 对每一个数组元素都执行 func 。
  • setTimeout(func) —— func 由内建调度器执行。

……还有更多。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);
    }
}

箭头函数总结:

  • 没有 this
  • 没有 arguments
  • 不能使用 new 进行调用
  • 它们也没有 super (在下一篇类继承中说明)
相关文章
相关标签/搜索