返回

模拟一下对象的 new 命令

前端

背景

JavaScript 提供了创建对象的两种主要方法。

  1. 使用字面量语法:
    const obj = {
      name: "John Doe",
      age: 30,
      greet: function() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
      }
    };
    
  2. 使用 new 操作符和构造函数:
    function Person(name, age) {
      this.name = name;
      this.age = age;
      this.greet = function() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
      }
    }
    
    const obj = new Person("John Doe", 30);
    

new 运算符的工作原理

new 运算符本质上做了以下几件事:

  1. 创建一个全新的空对象。
  2. 将这个对象作为 this 值传递给构造函数。
  3. 执行构造函数的主体(代码块)。
  4. 将构造函数的 this 值返回给 new 表达式。

模拟 new 运算符

我们可以模拟 new 运算符来更好地理解它的工作原理。要做到这一点,我们需要以下步骤:

  1. 创建一个函数来模拟构造函数。
  2. 使用 apply() 方法将模拟构造函数的 this 值设置为新创建的对象。
  3. 返回新创建的对象。

以下是如何模拟 new 运算符的代码示例:

function myNew(constructor, ...args) {
  const obj = {};
  constructor.apply(obj, args);
  return obj;
}

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const obj = myNew(Person, "John Doe", 30);

obj.greet(); // Hello, my name is John Doe and I am 30 years old.

总结

通过模拟 new 运算符,我们可以更好地理解它是如何工作的。这种技术可以在某些情况下非常有用,例如,当我们想要创建一个与现有构造函数兼容的新对象时。