new 操作符做了哪些事情?如何手写一个 new?

new 做了 4 件事

  1. 创建一个新的空对象
  2. 将新对象的 __proto__ 指向构造函数的 prototype
  3. 将构造函数的 this 绑定到新对象并执行
  4. 如果构造函数返回对象,则返回该对象;否则返回新对象

手写 new

function myNew(Constructor, ...args) {
  // 1. 创建新对象,原型指向构造函数的 prototype
  const obj = Object.create(Constructor.prototype)

  // 2. 执行构造函数,绑定 this
  const result = Constructor.apply(obj, args)

  // 3. 如果返回值是对象则使用该对象,否则返回新创建的对象
  return result instanceof Object ? result : obj
}

// 测试
function Person(name, age) {
  this.name = name
  this.age = age
}
Person.prototype.sayHi = function () {
  console.log('Hi, ' + this.name)
}

const p = myNew(Person, 'Tom', 25)
p.sayHi()  // 'Hi, Tom'

构造函数返回值的影响

function Foo() {
  this.name = 'foo'
  return { name: 'bar' }  // 返回对象 → 使用该对象
}
new Foo().name  // 'bar'

function Bar() {
  this.name = 'bar'
  return 'string'  // 返回原始值 → 忽略,使用 this
}
new Bar().name  // 'bar'

同分类其他题目