5

深入理解JavaScript中的箭头

 3 years ago
source link: http://www.cnblogs.com/alone4436/p/14402142.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

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

JavaScript 充满了我们需要编写在其他地方执行的小函数的情况。

例如:

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

……还有更多。

JavaScript 的精髓在于创建一个函数并将其传递到某个地方。 在这样的函数中,我们通常不想离开当前上下文。这就是箭头函数的主战场啦。

箭头函数没有 this 。如果访问 this ,则会从外 部获取。

const group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],

  showList() {
    this.students.forEach((student) => console.log(`${this.title}:${student}`));
  },
};

group.showList();

如何使用普通函数则会出现错误,原因如下:

this指向错误,因为函数调用的上下文并非是group

⚠ 不能对箭头函数进行 new 操作 不具有 this 自然也就意味着另一个限制:箭头函数不能用作构造器(constructor)。不能用 new 调用它们。
—《现代JavaScript教程》

箭头函数没有 “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 (在下一篇类继承中说明)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK