JS source code to achieve the new operator

First we look at an object instance of the browser did do something

The new four steps:

1. Create an empty object

2. Set the prototype property __proto__ empty object constructor property inheritance, i.e. public properties on prototype object inherits methods and constructors

3. Call the constructor, the constructor of this object is replaced with an empty this, inherited constructor property

4. Returns a new object inside the function

 Source code implementation

myNew function (Fun) { 
  return function () { 
    // create a new object and its implicit constructor prototype prototype point 
    the let {obj = 
      the __proto__: fun.prototype 
    } 
    // constructor is executed 
    fun.call (obj, .. .arguments) 
    // returns the object 
    return obj 
  } 
} 

function Person (name, Age) { 
  this.name name = 
  this.age = Age 
} 
the let obj = myNew (Person) ( 'Chen', 18 is) {// name: "chen", age: 18}

  

Guess you like

Origin www.cnblogs.com/jiajialove/p/11288255.html