What is new?

The new operator creates an instance of a user-defined object type or an instance of a built-in object with a constructor.

function Person (name,age) {
    this.name = name
    this.age = age
}
Person.prototype.sayName  = function () {
    console.log(this.name)
}
let man = new Person('xl',20)
console.log(man) // Person { name: 'xl', age: 20 }
man.sayName() // 'xl'
Copy the code
  • New creates an instance of Person that can access properties in the constructor
  • New creates an instance of Person that has access to methods and properties on the constructor prototype chain

What happens if you add a return value to the constructor?

  • Returns the basic data type
function Car (price) {
  this.price = price
  return 20
}
let bigCar = new Car(90)
console.log(bigCar.price) // 90
Copy the code

As you can see, the return value is ignored when the base data type is returned

  • Returns the reference data type
function Car (price) {
  this.price = price
  return { km: 200 }
}
let bigCar = new Car(90)
console.log(bigCar.price, bigCar.km) // undefined, 200
Copy the code

You can see that the return reference data type will be used normally

The new process

What did New do?

  • Create a new objectobj
  • Connect the and constructors of obj through the prototype chain
  • Will be the constructorthisPointing to the obj
  • Returns if the function returns no objectthis

Implement a new

function myNew (func, ... Args) {const obj = object.create (func.prototype) // object.create () method to create a new Object, Use the existing Object to provide the newly created Object's __proto__ let result = func.apply(obj, args) return result instanceof Object? result : obj } let p = myNew(Person, "huihui", 123) console.log(p) // Person {name: "huihui", age: 123} p.sayName() // huihuiCopy the code