JavaScript 中階
ES6 中的 class 是什麼?和函式構造函式差別是什麼?
ES6 Class 語法
ES6 引入了 class 關鍵字,提供更清晰的物件導向語法。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a sound.');
}
}
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
}
const d = new Dog('Rex');
d.speak(); // 'Rex barks.'
函式構造函式(ES5)
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a sound.');
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log(this.name + ' barks.');
};
主要差異
| 特性 | Class | 函式構造函式 |
|---|---|---|
| 語法 | 簡潔清晰 | 冗長複雜 |
| Hoisting | 不會提升(TDZ) | 會提升(函式宣告) |
| 嚴格模式 | 預設開啟 | 需要手動加 |
| 必須用 new | 強制(否則 TypeError) | 忘記 new 不會報錯 |
| 繼承 | extends + super |
手動設定 prototype |
| 靜態方法 | static 關鍵字 |
直接加在函式上 |
本質
Class 本質上是語法糖(Syntactic Sugar),底層仍是原型鏈繼承。
typeof class Foo {} // 'function'
✦ AI 模擬面試
輸入你的答案,AI 即時分析精準度與改進空間
登入後即可使用 AI 評分
