类
约 471 字大约 2 分钟
2026-02-26
ES6 的 class 不是全新对象模型,而是对“构造函数 + 原型”写法的语法升级。 它解决的是代码组织和可读性问题,让面向对象表达更直观。
从构造函数到 class
ES5 常见写法:
function Animal(name, age) {
this.name = name
this.age = age
}
Animal.prototype.print = function () {
console.log(`名字: ${this.name}`)
console.log(`年龄: ${this.age}`)
}这种写法可用,但“实例属性”和“原型方法”分散在两处。 class 把它们收拢到同一个结构里。
class Animal {
constructor(name, age) {
this.name = name
this.age = age
}
print() {
console.log(`名字: ${this.name}`)
console.log(`年龄: ${this.age}`)
}
}class 的本质
class 本质仍然是函数。
class Point {}
console.log(typeof Point) // function
console.log(Point === Point.prototype.constructor) // true但它和普通函数有一个关键限制:必须用 new 调用。
class User {}
new User() // OK
// User() // TypeError: Class constructor User cannot be invoked without 'new'构造器与实例成员
constructor 在 new 时自动执行。未显式定义时会有默认空构造器。
class Counter {
constructor(start = 0) {
this.count = start
}
inc() {
this.count += 1
return this.count
}
}访问器:get / set
访问器让属性读写可以携带校验与格式化逻辑。
class Person {
constructor(age) {
this.age = age
}
get age() {
return this._age
}
set age(value) {
if (typeof value !== 'number' || value < 0) {
throw new TypeError('age 必须是非负数字')
}
this._age = value
}
}静态成员
static 定义在类本身上,不会挂到实例上。
class MathTool {
static add(a, b) {
return a + b
}
}
console.log(MathTool.add(1, 2)) // 3私有字段(现代语法)
私有字段以 # 声明,只能在类内部访问。
class Wallet {
#balance = 0
deposit(n) {
this.#balance += n
}
getBalance() {
return this.#balance
}
}演示:实例属性、原型方法、静态方法
<!doctype html>
<html lang="zh-CN">
<body>
<pre id="out"></pre>
<script>
class Animal {
static kingdom = 'Animalia'
constructor(name, age) {
this.name = name
this.age = age
}
print() {
return `${this.name}(${this.age})`
}
}
const dog = new Animal('旺财', 3)
const lines = []
lines.push('实例方法调用: ' + dog.print())
lines.push('静态属性: ' + Animal.kingdom)
lines.push('hasOwn print: ' + dog.hasOwnProperty('print'))
lines.push(
'原型有 print: ' +
Object.prototype.hasOwnProperty.call(Animal.prototype, 'print')
)
document.getElementById('out').textContent = lines.join('\n')
</script>
</body>
</html>