Arrow functions revisited

JavaScript Arrow Functions Revisited (JavaScript箭头函数重新审视)

Arrow functions have both some useful and unique features and limitations that we are going to cover in this chapter. (箭头函数具有一些有用和独特的功能和局限性,我们将在本章中介绍。)

In JavaScript, you can meet a lot of cases when it’s necessary to write a small function, which is executed in another place. (在JavaScript中,当需要编写一个在另一个地方执行的小函数时,您可以遇到很多情况。)

To be more precise, let’s consider several examples:

arr.forEach(func) - for each array item func is executed by forEach. (arr.forEach (func) -对于每个数组项, func由forEach执行。)

setTimeout(func)- the built-in schedule executes func. (setTimeout (func) -内置调度执行func。)

There can be many other such examples, too. (也可能有许多其他这样的例子。)

The primary aim of JavaScript is to create a function and pass it somewhere. In circumstances like that, as a rule, you don’t wish to leave the current content. Arrow functions can help you in such situations. (JavaScript的主要目的是创建一个函数并将其传递到某个地方。 在这种情况下,作为一项规则,您不希望离开当前内容。 在这种情况下,箭头功能可以为您提供帮助。)

No “this” in Arrow Functions

No “this” in Arrow Functions (箭头函数中没有“this”)

There is no “this” in arrow functions. Even if it’s accessed, then it’s taken from the outside. (箭头函数中没有“this”。即使有人进入,也是从外面拿走的。)

For example, it can be used for iterating inside an object method like this:

let books = {
 title: "Our Books",
 booksTitle: ["Javascript", "HTML", "CSS"], 
 showList() {
   this.booksTitle.forEach(
(this.booksTitle.forEach ()
     book => console.log(this.title + ': ' + book)
   );
 }
};
books.showList();

In the example above, the arrow function is used in forEach. But, inside it, the this.title is the same as the showList outer method. It is the book.title. Note that in the event of using a regular function an error would occur:

let books = {
 title: "Our Books",
 booksTitle: ["Javascript", "HTML", "CSS"], 
 showList() { 
   this.booksTitle.forEach(function (book) {
     // Error: Cannot read property 'title' of undefined
     console.log(this.title + ': ' + book)
   });
 }
};
books.showList();

The reason for the error is that forEach runs functions using this=undefined by default. So, there is an attempt to access undefined.title. So, it will not impact on arrow functions because they have no this. Another important thing to note: you can’t use arrow functions as constructors. They may not be called with new.

Between an arrow function and a regular function, there is a subtle difference, called using .bind(this). It generates the functions bound version. The arrow => can’t create any binding, as it simply doesn’t include this. The lookup of this is generated the same way as the search of a regular variable inside the outer lexical environment. (在箭头函数和常规函数之间,有一个微妙的区别,称为使用.bind (this)。它生成函数绑定版本。箭头= >无法创建任何绑定,因为它根本不包括this。此查找的生成方式与在外部词法环境中搜索常规变量的方式相同。)

No argument variable exists in arrow functions. It is handy especially for decorators when forwarding a call is necessary with the current argument and this. (箭头函数中不存在参数变量。 当需要使用当前参数和this转发调用时,它尤其适用于装饰者。)

Let’s check out an example in which defer(f, ms) receives a function, returning a wrapper around it that delays the call by milliseconds:

No Arguments in the Arrows

No Arguments in the Arrows (箭头中无参数)

function defer(fn, ms) {
 return function () {
   setTimeout(() => fn.apply(this, arguments), ms)
(setTimeout (() = > fn.apply (this, arguments), ms))
 };
} 
function sayWelcome(where) {
 console.log('Welcome to ' + where);
}
let sayWelcomeDeferred = defer(sayWelcome, 1500);
sayWelcomeDeferred("w3cdoc"); // Welcome to w3cdoc after 1.5 seconds

In case of running the same function with arrow function, you will have the following:

function defer(fn, ms) {
 return function (...args) {
   let ctx = this;
   setTimeout(function () {
     return fn.apply(ctx, args);
   }, ms);
 };
}
function sayWelcome(where) {
 console.log('Welcome to ' + where);
}
let sayWelcomeDeferred = defer(sayWelcome, 1500);
sayWelcomeDeferred("w3cdoc"); // Welcome to w3cdoc after 1.5 seconds

In this example, there are additional variables such as ctx and args so that the function within the setTimeout can take them. (在此示例中,还有其他变量,例如ctx和args ,以便setTimeout中的函数可以获取它们。)

Summary

Summary (概要)

Arrow functions are useful in cases when it’s necessary to write a small function, which is executed in another place. (当需要编写一个在另一个地方执行的小函数时,箭头函数非常有用。)

To be brief, we can state that arrow functions don’t have this. They don’t have arguments, either. Also, you can’t call them using new. (简而言之,我们可以说箭头函数没有这个。他们也没有争论。此外,您不能使用NEW给他们打电话。)

As a rule, arrow functions are handy for short pieces of code that don’t have their context and operate within the current one. (通常,箭头函数适用于没有上下文并在当前上下文中操作的短代码片段。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部