In JavaScript, the ‘new’ keyword is used to create an instance object of a class (mock class). When an object is instantiated, it inherits the properties and methods of the class.
Execution Process
Create a new and empty object.
Set the new object prototype to point to class constructor.
Execute the constructor, binding the ‘this’ keyword.
If the constructor does not return an object, it returns this.
Simulate the ‘new’ keyword
use Object.create to simulate ‘new’ keyword
1 2 3 4 5 6 7 8 9 10 11
const newNew = function (Parent, ...args) { let newObj = Object.create(Parent.prototype); let res = Parent.apply(newObj, args); returntypeof res === "object" ? res : newObj; };
let object1 = new Base(); let object2 = newNew(Base);
// newNew const newNew1 = function (Parent, ...args) { // let newObject = {}; let newObject = Object(); newObject.__proto__ = Parent.prototype; let res = Parent.apply(newObject, args); returntypeof res === "object" ? res : newObject; };
let object1 = new Base(); let object2 = newNew(Base);