JavaScript面向对象核心在于prototype、this绑定和对象创建本质,class仅为原型链语法糖;构造函数需new调用,方法应挂prototype以复用;工厂函数更安全灵活,适合无需继承的场景。
JavaScript 中没有传统意义上的类(class)关键字(ES6 之前),但完全支持面向对象编程——关键不在于语法糖,而在于理解 prototype、this 绑定和对象创建的本质。
function 构造函数模拟类行为这是最基础也最容易出错的方式。构造函数本身只是普通函数,只有通过 new 调用时,this 才指向新对象。
new 调用,否则 this 指向全局(非严格模式)或 undefined(严格模式)prototype 上才可复用,直接在函数体内用 this.method = function(){} 会为每个实例重复创建函数Child.prototype = Object.create(Parent.prototype),并修复 constructor
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
return `Hello, I'm ${this.name}`;
};
const alice = new Person('Alice');
class 语法只是语法糖,底层仍是原型链ES6 的 class 看似像 Java/C#,但本质没改变 JavaScript 的原型机制。它不能定义私有字段(直到 #field 提案落地)、不支持多重继承、静态方法仍挂载在构造函数上。
class 声明不会被提升,必须先定义后使用super() 必须在子类 constructor 中调用,且必须在访问 this 前完成Object.keys() 不会返回它们),但 for...in 仍能遍历到原型上的方法class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}
new 和 this:工厂函数更安全当不需要共享方法、或想规避 this 绑定问题时,工厂函数(返回普通对象)更轻量、更可控,尤其适合配置对象、DTO 或小型工具封装。
prototype 链开销,每个属性/方法都是独立闭包# 或 WeakMap
instanceof 判断类型,但可用 typeof obj === 'object' && 'method' in obj 做鸭子检测function createCalculator(initial = 0) {
let value = initial;
return {
add(n) { value += n; return this; },
get() { return value; }
};
}
const calc = createCalculator(5).add(3);
console.log(calc.get()); // 8
很多人纠结该用 class 还是工厂函数,其实更关键的是:这个对象是否需要状态封装?是否需要多态?是否会被大量实例化?

class 更利于组织生命周期和继承关系Object.freeze({x, y}) 更高效原型链深了容易调试困难,this 绑定错一次就静默失败,这些比语法选择更值得花时间确认。