8、手写 new

42 阅读1分钟

前置知识:15、new 干了什么事情? - 掘金

由于new是关键词,所以我们手写时将其绑到Function.prototype上,方便使用

Function.prototype.New = function(...args) {
  // 构造函数
  const constructorFn = this
  
  // 1、创建一个空对象
  const obj = {}

  // 2、将该空对象的__proto__指向构造函数的 prototype
  obj.__proto__ = constructorFn.prototype
  
  // 3、将 this 指向该空对象
  const bindFn = constructorFn.bind(obj)
  
  // 4、执行构造函数
  const result = bindFn(...args)

  if(typeof result === 'obj') return result
  else return obj
}

// 具体使用:
function Person(name, age) {
  this.name = name
  this.age = age
}

const p1 = Person.New('张三', 35) // { name: '张三', age: 35 }

// p1 instanceof Person 为 true