Skip to content

new 的实现

new 是 JavaScript 中用于创建一个构造函数实例的操作符,它的核心作用是:

  1. 创建一个空对象;
  2. 将这个对象的原型指向构造函数的 prototype;
  3. 执行构造函数,并将 this 指向这个新对象;
  4. 如果构造函数返回的是对象类型,则返回该对象;否则返回步骤 1 创建的新对象。

我们可以手动实现一个 new 的行为,如下:

✅ 手写 new 的实现

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

  // 2. 执行构造函数,绑定 this 为新对象
  const result = constructor.apply(obj, args);

  // 3. 返回构造函数返回的对象(如果是对象类型),否则返回新对象
  return result !== null && (typeof result === 'object' || typeof result === 'function')
    ? result
    : obj;
}

✅ 示例用法

js
function Person(name) {
  this.name = name;
}
Person.prototype.sayHello = function () {
  console.log(`Hi, I'm ${this.name}`);
};

const p1 = myNew(Person, 'Alice');
p1.sayHello(); // Hi, I'm Alice
console.log(p1 instanceof Person); // true

✅ 对比原生 new

js
const p2 = new Person('Bob');
console.log(p2 instanceof Person); // true

🔍 小结

关键步骤:

  • 使用 Object.create 设置原型链。
  • 使用 apply 传递参数并绑定 this。
  • 处理构造函数返回对象类型的情况(这是 new 操作符和普通函数调用的最大区别之一)。