JavaScript作为一门支持面向对象编程的语言,早期通过构造函数和原型链实现对象创建和继承,ES6引入Class关键字后,为面向对象编程提供了更简洁的语法糖。两者在底层实现上其实有共通之处,但在使用方式和特性上存在不少差异。

基本语法对比
先看两种方式的创建对象的语法差异,构造函数通过函数定义,结合this绑定属性,而Class通过class关键字定义类结构。
构造函数写法
传统构造函数创建对象的方式如下:
// 定义构造函数
function Person(name, age) {
// 实例属性
this.name = name;
this.age = age;
}
// 原型上添加方法
Person.prototype.sayHello = function() {
console.log(`你好,我是${this.name},今年${this.age}岁`);
};
// 创建实例
const person1 = new Person('张三', 20);
person1.sayHello(); // 输出:你好,我是张三,今年20岁
Class关键字写法
使用Class关键字实现同样的功能:
// 定义类
class Person {
// 构造方法,对应构造函数的逻辑
constructor(name, age) {
this.name = name;
this.age = age;
}
// 类的方法直接定义在类内部,本质是添加到原型上
sayHello() {
console.log(`你好,我是${this.name},今年${this.age}岁`);
}
}
// 创建实例
const person1 = new Person('张三', 20);
person1.sayHello(); // 输出:你好,我是张三,今年20岁
核心特性差异
提升机制不同
构造函数存在函数提升,在定义之前就可以调用,而Class不存在提升,必须在定义之后才能使用。
// 构造函数提升示例
const p1 = new Person('李四', 22); // 正常执行,不会报错
function Person(name, age) {
this.name = name;
this.age = age;
}
// Class无提升示例
const p2 = new Student('王五', 18); // 报错:Cannot access 'Student' before initialization
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
严格模式差异
Class内部默认开启严格模式,而构造函数默认是非严格模式,除非手动声明use strict。
// 构造函数默认非严格模式
function Func() {
name = '测试'; // 不会报错,隐式创建全局变量
}
new Func();
console.log(name); // 输出:测试
// Class内部默认严格模式
class Cls {
constructor() {
name = '测试'; // 报错:name is not defined
}
}
new Cls();
静态成员定义方式
构造函数定义静态成员是直接给函数对象添加属性,Class通过static关键字定义。
// 构造函数静态成员
function Utils() {}
Utils.formatTime = function() {
return new Date().toLocaleString();
};
console.log(Utils.formatTime()); // 调用静态方法
// Class静态成员
class Utils {
static formatTime() {
return new Date().toLocaleString();
}
}
console.log(Utils.formatTime()); // 调用静态方法
继承实现对比
两种方式的继承实现差异较大,构造函数需要通过call绑定父构造函数this,再修改原型链,Class通过extends和super关键字实现。
构造函数继承
// 父类构造函数
function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function() {
console.log(`${this.name}在吃东西`);
};
// 子类构造函数
function Dog(name, breed) {
// 调用父类构造函数绑定this
Animal.call(this, name);
this.breed = breed;
}
// 修改子类原型指向父类实例,实现原型链继承
Dog.prototype = Object.create(Animal.prototype);
// 修正构造函数指向
Dog.prototype.constructor = Dog;
// 子类添加自己的方法
Dog.prototype.bark = function() {
console.log(`${this.name}在汪汪叫`);
};
const dog = new Dog('小黑', '金毛');
dog.eat(); // 输出:小黑在吃东西
dog.bark(); // 输出:小黑在汪汪叫
Class继承
// 父类
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name}在吃东西`);
}
}
// 子类继承父类
class Dog extends Animal {
constructor(name, breed) {
// 调用父类构造方法,必须在使用this之前调用
super(name);
this.breed = breed;
}
bark() {
console.log(`${this.name}在汪汪叫`);
}
}
const dog = new Dog('小黑', '金毛');
dog.eat(); // 输出:小黑在吃东西
dog.bark(); // 输出:小黑在汪汪叫
选择建议
如果是维护老项目,或者需要兼容不支持ES6的旧环境,优先选择构造函数写法;如果是新项目,且环境支持ES6及以上语法,推荐使用Class关键字,语法更清晰,继承等复杂逻辑实现更简单,也更符合其他面向对象语言的开发习惯。两者底层都基于原型链实现,最终生成的实例和原型结构是一致的,核心差异在于语法层面的表现。
JavaScriptClass构造函数面向对象原型链修改时间:2026-07-20 03:54:25