Understand arrow functions in depth

Let’s take a closer look at the arrow function.

The arrow function is not just a “shortcut” to writing clean code. It also has very special and useful properties.

JavaScript is full of situations where we need to write small functions that execute elsewhere.

Such as:

  • arr.forEach(func)forEachExecutes on each array elementfunc.
  • setTimeout(func)funcExecuted by the built-in scheduler.
  • … There’s more.

The essence of JavaScript is to create a function and pass it somewhere.

In such functions, we usually don’t want to leave the current context. This is where the arrow function comes in.

Arrow function doesn’t have “this”

As we learned in the “this” chapter on object methods, arrow functions do not have this. If you access this, you get it externally.

For example, we can use it to iterate inside object methods:

let group = {
  title: "Our Group".students: ["John"."Pete"."Alice"].showList() {
    this.students.forEach(
      student= > alert(this.title + ':'+ student) ); }}; group.showList();Copy the code

The arrow function is used in forEach, so this.title is exactly the same as the external method showList. That is: group.title.

If we use normal functions, we get an error:

let group = {
  title: "Our Group".students: ["John"."Pete"."Alice"].showList() {
    this.students.forEach(function(student) {
      // Error: Cannot read property 'title' of undefined
      alert(this.title + ':'+ student) }); }}; group.showList();Copy the code

ForEach is running this function, but this is the default value this=undefined, so we tried to access undefined. Title.

But arrow functions are fine, because they don’t have this.

Cannot be performed on arrow functionsnewoperation

The absence of this naturally implies another limitation: arrow functions cannot be used as constructors. You cannot call them with new.

Arrow function VS bind

There are subtle differences between the arrow function => and the regular function called with.bind(this) :

  • .bind(this)A “bound version” of the function is created.
  • Arrow function= >No bindings were created. The arrow function just doesn’t have onethis.thisIs searched in exactly the same way as regular variables: in an external lexical context.

Arrow functions don’t have “arguments”

Arrow functions also don’t have arguments variables.

This is useful for decorators when we need to forward a call using the current this and arguments.

For example, defer(f, ms) takes a function and returns a wrapper that calls delay MS milliseconds:

function defer(f, ms) {
  return function() {
    setTimeout(() = > f.apply(this.arguments), ms)
  };
}

function sayHi(who) {
  alert('Hello, ' + who);
}

let sayHiDeferred = defer(sayHi, 2000);
sayHiDeferred("John"); // After 2 seconds: Hello, John
Copy the code

Instead of using the arrow function, you could write:

function defer(f, ms) {
  return function(. args) {
    let ctx = this;
    setTimeout(function() {
      return f.apply(ctx, args);
    }, ms);
  };
}
Copy the code

Here, we must create additional variables args and CTX so that the function inside setTimeout can get them.

conclusion

Arrow function:

  • There is nothis
  • There is noarguments
  • You can’t usenewThe calling
  • They don’t eithersuperBut we haven’t learned that yet. We will be inClass inheritanceLearn it in chapter 1.

This is because arrow functions are for short code that has no “context” of its own, but works in the current context. And the arrow function really shines in this usage scenario.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Search the official wechat account “Technology Talk” and subscribe for more exciting content.