new is not so easy to achieve

Speaking of JavaScript among the new keyword has a very interesting history. In fact, JavaScript creator Brendan Eich achieve new in order to obtain a higher popularity, it is forced to learn a residual output of Java, he wanted to become a Java JavaScript little brother. Many people think that JavaScript is designed to cover up the real prototype inheritance, just on the surface, like a class-based inheritance.

This misunderstanding makes many traditional Java developers are not well understood JavaScript. In fact, we should understand front-end engineers, new keywords in the end to do something.

  • step1: After first create an empty object that will serve as the implementation of the new constructor () returns the object instance
  • step2: empty object prototype created above ( __proto__), point constructor prototype property
  • step3: The object is assigned to the empty interior of this constructor, and the constructor is executed logic
  • step4: The execution logic constructor or a constructor returns the object created in step explicit return value

Because JavaScript is a new keyword, we can not directly covered achieve a newFunc to simulate expected use:

function Person(name) {
  this.name = name
}

const person = new newFunc(Person, 'lucas')

console.log(person)

// {name: "lucas"}

  

Implemented as:

newfunc function (args ...) { 
  // take the first parameter args array, i.e. target constructor 
  const = args.shift constructor () 

  // Create an empty object, and the attribute inheritance prototype null object constructor 
  // i.e. .__ proto__ === constructor.prototype achieve obj 
  const obj = the Object.create (constructor.prototype) 

  // constructor is executed, the result obtained constructor returns 
  // Note that we use Apply, to this point in the constructor for the obj 
  constructor.apply the result = const (obj, args) 

  // If the constructors execution, the result is an object type, direct return, otherwise the object obj 
  return (typeof result === 'object' && result! = null)? the Result: obj 
}

  

The code is not complicated, several key points:

  • The use of obj Object.create  point prototype constructor __proto__
  • The method of use apply, this will be directed to the obj constructor
  • When newFunc return, determined using the ternary operator returns the result

We know that, if the constructor has an explicit return value, and returns a value of the object type, then the constructor returns a result is no longer certain instances. The following code:

function Person(name) {
  this.name = name
  return {1: 1}
}

const person = new Person(Person, 'lucas')

console.log(person)

// {1: 1}

  

Note that understand these points, to understand the implementation newFunc is no longer difficult.

Guess you like

Origin www.cnblogs.com/yipinxuan/p/11275198.html