new 操作符的执行过程

理解 new 操作符做了什么,并手写实现

问题

new 操作符在 JavaScript 中具体执行了哪些步骤?如何手写实现一个 new

解答

new 的执行步骤

  1. 创建一个空对象
  2. 将空对象的原型指向构造函数的 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, I'm ${this.name}`);
};

// 使用原生 new
const p1 = new Person('Alice', 25);
p1.sayHi(); // Hi, I'm Alice

// 使用 myNew
const p2 = myNew(Person, 'Bob', 30);
p2.sayHi(); // Hi, I'm Bob

console.log(p2 instanceof Person); // true

构造函数返回值的情况

// 返回对象时,new 返回该对象
function Foo() {
  this.a = 1;
  return { b: 2 };
}
const foo = new Foo();
console.log(foo); // { b: 2 }

// 返回基本类型时,忽略返回值
function Bar() {
  this.a = 1;
  return 'hello';
}
const bar = new Bar();
console.log(bar); // { a: 1 }

关键点

  • 创建新对象并链接原型链(Object.create
  • 执行构造函数并绑定 thisapplycall
  • 构造函数返回对象则使用该对象,否则返回新创建的对象
  • 返回基本类型会被忽略,仍返回新对象