JavaScript 构造函数

使用构造函数来创建具有相同结构的多个对象。

构造函数充当蓝图。你使用 new 关键字根据此蓝图构建对象。构造函数的名称应当以大写字母开头。

工作原理:

当你使用 new 关键字时,JavaScript 会执行四个步骤:

this 关键字至关重要。在函数内部,this 指向你的新对象。

示例:

function Employee(name, salary) {
    this.name = name;
    this.salary = salary;
}

const emp1 = new Employee("Ram", 50000);
const emp2 = new Employee("Kumar", 60000);

两个对象共享相同的结构。

添加方法:

你可以在构造函数内部添加函数。

function Employee(name, salary) {
    this.name = name;
    this.salary = salary;
    this.displayInfo = function() {
        console.log(this.name + " earns " + this.salary);
    };
}

内存管理:

直接在构造函数内部添加方法会为每个对象创建一个新的副本。这会消耗更多内存。

相反,请使用 prototype 属性。

Employee.prototype.greet = function() {
    console.log("Hello " + this.name);
};

现在,每个员工都共享 greet 方法的一个单一副本。这会让你的代码更加高效。

总结:

Source: https://dev.to/dev_saravanan_journey/javascript-constructor-functions-k6k