new

What did New do

  • A brand new object is created
  • Instances and constructors are linked by a stereotype chain
  • The constructor is executed using the empty object as the constructor’s this context
  • Return a new object

Implement a new

Function testNew (fn) {// Get the argument passed; const args = [].slice.call(arguments, 1); // Create a new object const newObj = {}; Object.setprototypeof (newObj, fn.prototype) // This points to the new Object fn.apply(newObj, args); Return newObj}Copy the code

Comparing to see

Function Person(name) {this.name = name} const obj = new Person(' hello ') function testNew (fn) { const args = [].slice.call(arguments, 1); // Create a new object const newObj = {}; Object.setprototypeof (newObj, fn.prototype) // This points to the new Object fn.apply(newObj, args); Return newObj} const testObj = testNew(Person, 'hello ') console.log(obj, testObj,' test ');Copy the code

It’s exactly the same

But notice that if you return an object from the constructor then you’re going to return the object from the constructor, so we’re going to have to change it a little bit

Function testNew (fn) {// Get the argument passed; const args = [].slice.call(arguments, 1); // Create a new object const newObj = {}; Object.setprototypeof (newObj, fn.prototype) const fnObj = fn.apply(newObj, args); // Return fnObj instanceof Object? fnObj : newObj; }Copy the code