ES6的class本质是构造函数的语法糖,底层仍基于原型机制;它用class关键字声明,含constructor、实例方法和静态方法,不提升、默认严格模式,必须new调用,方法不可枚举,继承通过extends+super实现。
ES6 的 class 本质是构造函数的语法糖,写法更清晰、语义更明确,但底层仍基于原型机制;它不是全新对象模型,而是对传统构造函数的封装和增强。
使用 class 关键字声明,内部用 constructor 定义构造方法,用简洁语法定义实例方法和静态方法:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 实例方法(自动添加到原型上)
sayHello() {
return `Hello, I'm ${this.name}`;
}
// 静态方法(直接挂在类上)
static createAnonymous() {
return new Person('Anonymous', 0);
}
}
注意:class 声明不会被提升(hoisting),必须先定义再使用;且默认启用严格模式。
prototype,方法直接写在类体中,自动挂载到原型new 调用:类构造器不能像普通函数那样直接调用,否则报 TypeError
enumerable: false),而手动挂到 prototype 上的方法默认可枚举extends + super() 实现继承,避免了传统组合继承/寄生组合继承的手动处理(如 Object.setPrototypeOf 或 Sub.prototype = Object.create(Super.prototype))static #privateField、#name 等,传统函数需靠闭包或 WeakMap 模拟编译或运行时,Babel 或 JS 引擎会把 class 编译为等价的函数+原型操作。例如:
// 这段 class
class Animal {
constructor(type) {
this.type = type;
}
speak() { console.log('...'); }
}
// 等价于
function Animal(type) {
this.type = type;
}
Animal.prototype.speak = function() { console.log('...'); };
所以 typeof Animal 仍是 "function",Animal.prototype.constructor === Animal 也成立。
变量提升,必须先声明后使用for...in 遍历时不可见),但可通过 Object.getOwnPropertyNames() 查看super.methodName()),而传统函数需手动保存父构造器引用this),也不应放在 constructor 中用于定义实例方法本质上,ES6 类让面向对象写法更接近其他语言习惯,降低了原型链理解门槛,但没改变 JavaScript 的原型本质。用好它,关键还是理解背后的原型和 this 绑定逻辑。