The new operator
For javascript inheritance, instantiate the constructor using the new operator, like let obj = new Fn() so what does new call the constructor of the class do? Today I’m going to implement the principle of new.
Second, simulate the implementation of new
Let’s first define a constructor:
function People(name) {
this.name = name; // Attributes on the instance
}
People.prototype.say = function () {
console.log('haha')}let ada = new People('ada');
console.log(ada.name); // 'ada'
ada.say(); // 'haha'
Copy the code
As you can see, using new implements subclasses that inherit the properties and methods of their People parent class. So let’s implement new
function myNew() {
let Constructor = Array.prototype.shift.call(arguments) Constructor = shift ()
let obj = {} // create a new object in memory
obj._proto_ = Constructor.prototype The _proto_ pointer to the new object points to the prototype property of the constructor
let r = Constrcutor.apply(obj,arguments); // 4, this points to the new object and executes the constructor code
return r instanceof Object ? r : obj // If the constructor returns an object, it returns that object, otherwise it returns a new object, obj
}
let ada = myNew(People, 'ada')
console.log(ada)
Copy the code
Third, summary
As a result, calling the class’s constructor with the new operator does the following:
- Create a new object in memory
- The _proto_ pointer inside this new object is assigned to the constructor’s Prototype property
- The this inside the constructor points to the new object
- Execute the code inside the constructor
- If the constructor returns a non-empty object, that object is returned; Otherwise, the newly created object is returned