An interview question about rewriting built-in new;

We won’t go into details about what new does, as we did in the article constructor creating custom classes

The original interview questions are as follows:

function Dog(name) {
    this.name = name;
}
Dog.prototype.bark = function () {
    console.log('wangwang');
}
Dog.prototype.sayName = function () {
    console.log('my name is ' + this.name);
}
/* let sanmao = new Dog(' sanmao '); sanmao.sayName(); sanmao.bark(); * /
//=> Based on the built-in new keyword, we can create an instance of Dog, SanMAO, which can retrieve the properties and methods on the prototype. Now we need to implement a _new method by ourselves, and also simulate the results after the built-in new
function _new() {
    Finish your code

}
let sanmao = _new(Dog, 'three hairs');
sanmao.bark(); //=>"wangwang"
sanmao.sayName(); //=> < span style = "max-width: 100%; clear: both;
console.log(sanmao instanceof Dog); //=>true
Copy the code

Built-in New analysis

sanmao = new Dog('three hairs');
// Start by executing Dog as a normal function (private context, parameter assignment, scope chain, variable promotion, code execution...)There are several things to be aware of when executing constructors:// Special 1: create an object (this object is an instance of the current class.__proto__ === class.prototype)
// Special 2: and have THIS in the function refer to the object being created
// Special 3: Returns the created instance object if the function does not return a result or returns a basic data value

Copy the code

Implementation approach

* @params * Fn: pass an instance of any class that you want to create * @return * Fn: an instance of this class */IE doesn't allow us to manipulate __proto__let obj = {};
    obj.__proto__ = Fn.prototype; //=> So this method passes

Object.create: Creates an empty object with XXX as its prototype (i.e. obj.__proto__=== XXX).Copy the code

The implementation code is as follows


function _new(Fn,... args) {
  // create instance object OBJ (obj.__proto__=== fn.prototype)
  let obj = Object.create(Fn.prototype);
  
  // When we execute Fn (a normal function), we need THIS in Fn to point to the instance object OBJ
  let result = Fn.apply(obj, args);
  
  // Return the created instance object (provided that the Fn execution does not return a reference value such as an object)
  if(result ! = =null && (typeof result === "object" || typeof result === "function")) {
    return result;
  }
  return obj;
}
Copy the code

Remove the comment

function _new(Fn,... args) {
  let obj = Object.create(Fn.prototype);
  let result = Fn.apply(obj, args);
  if(result ! = =null && (typeof result === "object" || typeof result === "function")) {
    return result;
  }
  return obj;
}
Copy the code