Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Analysis of arrow function and ordinary function

What is an arrow function? Let’s start with a simple impression.

fnName = (args) = > {
  console.log(args);
}
Copy the code

What about ordinary functions?

function fnName(args){
  console.log(args);
}
Copy the code

They seem very similar. So what’s the difference?

The arrow function is simpler

The arrow function uses three symbols instead of the eight-letter keyword function.

But if that were all it was, it would be superfluous.

From the point of view of this, the arrow function’s this point does not change because of the function.

If you don’t understand, you can finish reading the following paragraph.

The reference to this of ordinary functions can change depending on the execution context at runtime, which has led to numerous articles on the reference to this of functions. It’s also a pain point in development.

Arrow functions depend only on the context in which they are defined. Basically, when you type code, the context you see is the context of the arrow function.

Arrow function versus normal function

The difference between

  1. The this object inside the arrow function is the object at which it is defined, not used.

  2. Arrow functions do not have arguments. If you want to use arrow functions, you can use rest arguments instead.

  3. Arrow functions cannot be constructors; new cannot be used

  4. Arrow functions have no archetype and cannot be inherited

  5. Arrow functions should not be treated as Generator functions and the yield keyword should not be used

  const fn1 = (. numbers) = > {
    console.log(this)  // window
    console.log(numbers) / / [123]
    console.log(arguments) // error
  };
  const fn2 = function () {
    console.log(this) // window
    console.log(arguments) / / [123]
  }

  fn1(123);
  fn2(123);
Copy the code