This article is participating in the nuggets team online activity, clickCheck spring recruitment positions in big factories

1. Title Description

Implement a new keyword

Second, train of thought analysis

The new keyword is used to create objects. So what happens when you create an object

  • An object is created
  • Make sure this points to
  • Execute constructor
  • Return this object

Three, code implementation

function newFn(ConstructorFn, ... args) {
  // Create a box of objects
  let obj = {}
  // Point __proto__ to the prototype of the constructor
  obj.__proto__ = ConstructorFn.prototype
  // Execute the constructor to bind this
  let res = ConstructorFn.apply(obj, args)
  // Return the object
  return typeof res === 'object' ? res : obj
}

function Person(name, age) {
  this.name = name
  this.age = age
}

var per1 = newFn(Person, 'Joe'.28)
// console.log(per1.__proto__ == per2.__proto__)
console.log(per1)
const per2 = new Person('bill'.29)
console.log(per2)
console.log(per1.__proto__ == per2.__proto__) //true, both point to the prototype of the constructor
Copy the code

Four,

Need to understand the prototype chain, this part is too complicated, give two pictures to feel for yourself