说说new操作法具体干了什么?

2024-07-20 15:08:15 149
在JavaScript中,`new` 操作符用于创建一个由构造函数定义的对象实例。使用 `new` 操作符调用构造函数时,会执行以下几个步骤:

new 执行过程

  1. 创建一个新的空对象

    • 创建一个新对象,并将其 [[Prototype]] 设置为构造函数的 prototype 属性。
  2. 将构造函数的 this 指向这个新对象

    • 通过构造函数的 this 关键字,初始化新对象。
  3. 执行构造函数代码

    • 执行构造函数中的代码,对新对象进行属性和方法的初始化。
  4. 返回新对象

    • 如果构造函数显式返回一个对象(通常是显式返回非 null 的对象),则 new 表达式的值就是这个对象。否则,返回上面创建的新对象。

详细步骤

假设有一个构造函数 Person

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}`);
};

使用 new 操作符来创建 Person 的实例:

let person1 = new Person('Alice', 30);

下面是 new Person('Alice', 30) 具体执行的步骤:

  1. 创建一个新对象

    let newObj = {};
    
  2. 将新对象的 [[Prototype]] 设置为构造函数的 prototype 属性

    newObj.__proto__ = Person.prototype;
    
  3. 将构造函数的 this 指向这个新对象,并执行构造函数代码:

    let result = Person.call(newObj, 'Alice', 30);
    
  4. 返回新对象

    • 如果构造函数返回一个对象(非 null),则返回该对象:
      if (typeof result === 'object' && result !== null) {
        return result;
      }
      
    • 否则,返回新创建的对象 newObj
      return newObj;
      

例子

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}`);
};

let person1 = new Person('Alice', 30);
person1.sayHello(); // Hello, my name is Alice
console.log(person1 instanceof Person); // true
console.log(person1 instanceof Object); // true

在这个例子中:

  • new Person('Alice', 30) 创建了一个新对象 person1
  • 这个新对象的原型被设置为 Person.prototype,因此 person1 可以访问 Person.prototype 上定义的属性和方法。
  • 构造函数 Person 初始化了 person1nameage 属性。

总结

  • new 操作符创建一个新对象。
  • 将构造函数的 this 绑定到这个新对象。
  • 执行构造函数代码,对新对象进行初始化。
  • 返回这个新对象,除非构造函数显式返回一个非 null 的对象。