手写一个简化版 new

50 阅读1分钟

4. 手写一个简化版 new

function myNew(constructor, ...args) {
  const obj = Object.create(constructor.prototype); // 创建对象并继承原型
  const result = constructor.apply(obj, args);      // 执行构造函数
  return result instanceof Object ? result : obj;   // 返回结果
}

function Greet(name) {
  this.name = name;
}
const a = myNew(Greet, "Tom");
console.log(a.name);          // "Tom"
console.log(a instanceof Greet); // true

1. 为什么不是直接 return result

构造函数调用规则 里有一条:

  • 如果构造函数 显式返回一个对象(引用类型),那么这个对象会作为 new 表达式的结果。
  • 如果构造函数没有返回,或者返回一个 原始值(string/number/boolean/null/undefined/symbol/bigint),那么会忽略掉这个返回值,默认返回新建的对象

2. 举个例子

✅ 返回对象时生效

function Foo() {
  return { a: 1 };  // 显式返回对象
}

const f = new Foo();
console.log(f); // { a: 1 }
console.log(f instanceof Foo); // false ❌ (因为返回的是别的对象)

✅ 返回原始值时被忽略

function Bar() {
  this.x = 10;
  return 42; // 返回原始值
}

const b = new Bar();
console.log(b.x); // 10
console.log(b instanceof Bar); // true ✅ (返回的是默认的 this 对象)