Knowledge decomposition

Concept of arrow function

** Arrow function expressions ** have a cleaner syntax than function expressions and don’t have their own this, arguments, super, or new.target. The arrow function expression is more useful where anonymous functions are needed, and it cannot be used as a constructor.

  • There is no single this
  • Do not bind the arguments
  • Arrow functions cannot be used as constructors; using them with new throws an error
  • Arrow functions have no prototype attribute

Arrow functions are different from normal functions

function Person(name) {
  this.name = name
}
const person = name= > {
  this.name = name
}

console.dir(Person)
console.dir(person)
Copy the code

  • The lack of the arguments
  • Missing caller – Unable to determine context
  • The lack of the prototype

As can be seen from the above results, arrow functions are missing a lot of things compared to constructors, such as caller, arguments, and Prototype.

By simulating the function

function myNew(fn, ... args) {
  // Create an empty object
  const obj = {};
  // Link the __proto__ attribute of this object to the constructor prototype object
  // ❌ is missing fn.prototype
  obj.__proto__ = fn.prototype;
  // Call the constructor as this context and receive the return value
  // ❌ does not have its own this
  The ❌ call() function cannot change the direction of the arrow function
  const res = fn.apply(obj, args);
  The constructor returns the value if it exists and is a reference data type, otherwise the created object is returned
  return typeof res === "object" ? res : obj;
}

Copy the code

Without these three generals, the instantiation process will be affected everywhere. So the conclusion that you can’t use arrow functions as constructors is self-evident.

The interview guide

  • First, the difference between the arrow function and the constructor is analyzed
    • The lack of the arguments
    • Missing caller – Unable to determine context
    • The lack of the prototype
  • Layer by layer analysis through the instantiation process

review

  • It’s too direct to ask new what happened to a function, so it’s easy to tell who’s memorizing the answer and not thinking.

Support but uncle

Pay attention to the public number [front-end bus] and Ran Uncle together