The principle of the new

  • Create an object obj. And sets the stereotype of this object to the stereotype of the constructor
  • Pass the constructor’s this to obj. And execute the constructor. Return ret after constructor execution
  • If the return is not an object, then obj needs to be returned. If it is an object, the RET is returned.
function NewFn(constructor, ... Rest) {// Create an object. Let obj = object.create (constructive.prototype); // Pass the constructor's this to obj. And execute the constructor. Let ret = constructor. Apply (obj, rest); // If the return is not an object, obj needs to be returned. If it is an object, the RET is returned. return typeof ret === 'object' ? ret : obj; }Copy the code

perform

function Person(name){
    this.name = name;
    console.log(this.name);
  }
  let zhangsan  = NewFn(Person, ' zhangsan');
  console.log(zhangsan);
Copy the code