JavaScript 构造器进阶:掌握 “new” 的底层原理,写出更优雅的代码!

12 阅读2分钟

一、构造器的本质与设计哲学

在JavaScript中,构造器本质上是普通函数,但遵循两大核心约定:

  • 命名首字母大写(如User
  • 必须通过new操作符调用。

这种设计源于面向对象编程的需求——当需要批量创建具有相同属性和方法的对象时,构造器通过封装创建逻辑,让代码复用效率提升。

例如商品对象创建:

function Product(name, price) {
  this.name = name;
  this.price = price;
  this.discount = 0;
}
const iphone = new Product("iPhone15", 6999);

通过new Product()可以快速生成成千上万的商品实例,这种模式比字面量创建方式节省了大量的代码。

二、new操作符的底层运行机制

  1. 创建一个新对象。
  2. 将新对象的原型指向构造器的prototype属性。
  3. 将构造器内部的this绑定到新对象。
  4. 执行构造器函数中的代码。
  5. 如果构造器函数没有显式返回对象,则返回新创建的对象。

示例

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

const john = new Person('John', 30);
john.sayHello(); // 输出: Hello, my name is John and I am 30 years old.

在这个例子中,new Person('John', 30)创建了一个新的Person对象,并将其赋值给变量john。我们可以调用johnsayHello方法,输出相应的信息。

三、使用构造器和"new"的注意事项

  1. 确保使用new:如果忘记使用new操作符调用构造器,this将指向全局对象(在浏览器中是window),而不是新创建的对象。这可能导致意外的行为。

    const jane = Person('Jane', 25); // 忘记使用 new
    console.log(jane); // 输出: undefined
    
  2. 返回对象:如果构造器函数显式返回一个对象,new操作符将返回该对象,而不是新创建的对象。

    function Animal(name) {
        this.name = name;
        return { type: 'Animal' }; // 返回一个对象
    }
    
    const dog = new Animal('Dog');
    console.log(dog); // 输出: { type: 'Animal' }
    
  3. 使用类语法:ES6引入了类的概念,使得构造器的定义更加简洁和易读。

    class Car {
        constructor(brand, model) {
            this.brand = brand;
            this.model = model;
        }
        display() {
            console.log(`Car: ${this.brand} ${this.model}`);
        }
    }
    
    const myCar = new Car('Toyota', 'Corolla');
    myCar.display(); // 输出: Car: Toyota Corolla