类的本质:不只是语法糖
JavaScript类(ES2015引入)表面类似传统面向对象语言,实则基于原型链机制:
class Person {
constructor(name) {
this.name = name
}
greet() {
return `Hello, ${this.name}!`
}
}
// 等效于旧式写法
function Person(name) {
this.name = name
}
Person.prototype.greet = function() {
return `Hello, ${this.name}!`
}
进阶特性与继承机制
类的继承通过extends关键字实现,比原型继承更直观:
class Developer extends Person {
constructor(name, language) {
super(name)
this.language = language
}
code() {
return `${this.name} is coding in ${this.language}`
}
// 重写父类方法
greet() {
return `${super.greet()} I'm a developer.`
}
}
const dev = new Developer('Alice', 'JavaScript')
console.log(dev.greet()) // "Hello, Alice! I'm a developer."
静态方法与私有字段
ES2022引入了真正的私有字段:
class ApiClient {
static version = '1.0' // 静态属性
#baseURL // 私有字段
constructor(baseURL) {
this.#baseURL = baseURL
}
static getVersion() { // 静态方法
return this.version
}
#buildEndpoint(path) { // 私有方法
return `${this.#baseURL}${path}`
}
async fetchData(path) {
const response = await fetch(this.#buildEndpoint(path))
return response.json()
}
}
总结
JavaScript类提供了更清晰的语法结构和更强的表达能力,但其底层仍基于原型系统。掌握类的本质和高级用法,能够编写更健壮、可维护的代码,适应现代前端开发需求。
理解类的实现原理,才能在框架设计中游刃有余
500

被折叠的 条评论
为什么被折叠?



