类的继承与修饰器模式
约 529 字大约 2 分钟
2026-02-26
继承的目标不是“少写代码”,而是把公共能力放在父类,让子类只关注自己的差异。 ES6 用 extends 和 super 明确了这套关系。
extends:建立父子类关系
class Animal {
constructor(name) {
this.name = name
}
speak() {
return `${this.name} makes a sound`
}
}
class Dog extends Animal {
bark() {
return `${this.name} woof!`
}
}super 的两种角色
super 在子类里有两种完全不同的含义。
1. 作为函数:super(...)
在子类构造器中调用父类构造函数。 在 super() 执行前不能使用 this。
class Animal {
constructor(name) {
this.name = name
}
}
class Dog extends Animal {
constructor(name, age) {
super(name)
this.age = age
}
}2. 作为对象:super.method()
在实例方法中,super 指向父类原型; 在静态方法中,super 指向父类本身。
class Animal {
speak() {
return 'animal sound'
}
static type() {
return 'animal'
}
}
class Dog extends Animal {
speak() {
return super.speak() + ' + dog bark'
}
static type() {
return super.type() + ':dog'
}
}演示:super 在实例与静态方法中的行为
<!doctype html>
<html lang="zh-CN">
<body>
<pre id="out"></pre>
<script>
class Animal {
constructor(name) {
this.name = name
}
speak() {
return this.name + ': animal sound'
}
static kind() {
return 'Animal'
}
}
class Dog extends Animal {
constructor(name) {
super(name)
}
speak() {
return super.speak() + ' -> woof'
}
static kind() {
return super.kind() + ' -> Dog'
}
}
const dog = new Dog('旺财')
document.getElementById('out').textContent = [
dog.speak(),
Dog.kind()
].join('\n')
</script>
</body>
</html>修饰器模式(Decorator)是什么
修饰器模式的核心是: 在不改动原对象主结构的前提下,为其附加能力。
在 JavaScript 工程里,“Decorator”通常指 @xxx 语法, 它是对类、方法、字段进行声明式增强的机制。
语法示例(TypeScript)
方法修饰器
function logCall(
_target: unknown,
key: string,
descriptor: PropertyDescriptor
) {
const original = descriptor.value
descriptor.value = function (...args: unknown[]) {
console.log(`[${key}] 参数:`, args)
return original.apply(this, args)
}
}
class UserService {
@logCall
getUser(id: number) {
return { id, name: 'zs' }
}
}类修饰器
function sealed<T extends new (...args: any[]) => any>(Ctor: T) {
Object.seal(Ctor)
Object.seal(Ctor.prototype)
}
@sealed
class Config {}工程配置提示
是否可用 @decorator 与构建链有关,不是 ES6 自带即可直接运行。 常见路径是:
- TypeScript 项目开启对应编译选项。
- 或通过 Babel 插件转换装饰器语法。
Decorator 和 Proxy 都是“增强能力”的手段, 但侧重点不同:前者是声明式扩展,后者是运行时拦截。
