JavaScript中构造函数用于初始化对象,首字母大写,通过new调用并用this设置属性;方法宜挂载prototype以复用;class是其语法糖,底层仍基于原型链。

在 JavaScript 中,用构造函数初始化实体,就是通过 new 操作符调用一个函数,让该函数为新创建的对象设置初始属性和方法。
构造函数的基本写法
构造函数本质上是普通函数,但习惯上首字母大写,且需配合 new 使用。它内部通常用 this 绑定实例属性:
- 函数名首字母大写(如
Person),便于区分普通函数 - 函数体中用
this.属性名 = 值初始化实例属性 - 可直接在
this上定义方法,也可挂载到prototype上以节省内存
示例:
function Person(name, age) {
this.name = name;
this.age = age;
}
const alice = new Person('Alice', 28); // 初始化一个实体
console.log(alice.name); // 'Alice'
避免常见错误:忘记 new
如果调用时漏掉 new,函数会作为普通函数执行,this 指向全局对象(非严格模式)或 undefined(严格模式),导致意外行为:
立即学习“Java免费学习笔记(深入)”;
- 非严格模式下:
Person('Bob', 30)会让name和age挂到window(浏览器)或global(Node.js)上 - 严格模式下:直接报错
Cannot set property 'name' of undefined - 可在构造函数开头加防护:检查
this是否为当前类型的实例,不是则自动补new
结合 prototype 实现方法复用
把方法定义在构造函数内部,每次新建实例都会重复创建函数,浪费内存。更合理的方式是把共享方法放在 prototype 上:
Person.prototype.sayHello = function() { ... }- 所有
Person实例都能访问该方法,且只有一份函数体 - 实例属性仍由构造函数初始化,方法由原型链提供
示例:
function Car(brand, year) {
this.brand = brand;
this.year = year;
}
Car.prototype.start = function() {
console.log(`${this.brand} car started.`);
};
const myCar = new Car('Toyota', 2022);
myCar.start(); // 'Toyota car started.'
现代替代方案:class 语法(本质仍是构造函数)
ES6 的 class 是构造函数的语法糖,底层仍基于原型链,写起来更清晰:
-
constructor()方法对应传统构造函数逻辑 - 类中定义的方法自动挂载到
prototype - 支持
static方法、继承(extends)、私有字段(#field)等特性
示例:
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const dog = new Animal('Buddy', 'Dog');
dog.speak(); // 'Buddy makes a sound.'


















