function Shape(x, y) {
// 公有屬性
this.x = x;
this.y = y;
// 私有變數(閉包)
let _id = Shape._nextId++;
// 特權方法存取私有變數
this.getId = () => _id;
}
Shape._nextId = 0;
const s = new Shape(1, 2);
console.log(s.x, s.y, s.getId()); // 1 2 0
Shape.prototype = {
move(dx, dy) { this.x += dx; this.y += dy; },
toString() { return `Shape(${this.x},${this.y})`; }
};
Shape.count = 0;
Shape.createOrigin = () => new Shape(0, 0);
function Circle(x, y, r) {
Shape.call(this, x, y); // 繼承實例屬性
this.r = r;
}
// 原型繼承
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
// 擴充/覆寫
Circle.prototype.area = function() { return Math.PI * this.r ** 2; };
Circle.prototype.toString = function() { return `Circle(${this.x},${this.y}, r=${this.r})`; };
class Shape {
static count = 0;
#id; // 私有欄位 (Stage 3, 現代瀏覽器/Node 12+ 支援)
constructor(x, y) {
this.x = x; this.y = y;
this.#id = Shape.count++;
}
getId() { return this.#id; }
move(dx, dy) { this.x += dx; this.y += dy; }
toString() { return `Shape(${this.x},${this.y})`; }
static createOrigin() { return new Shape(0, 0); }
}
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
area() { return Math.PI * this.r ** 2; }
toString() { return `Circle(${this.x},${this.y}, r=${this.r})`; }
}
| 場景 | 問題 | 解決 |
|---|---|---|
事件處理器 el.onclick = obj.handler | this 指向 el | 箭頭函數屬性 handler = () => {}、.bind(this)、addEventListener(e => this.handler(e)) |
回呼傳遞 setTimeout(obj.method, 100) | this 丟失 | setTimeout(() => obj.method(), 100) 或 obj.method.bind(obj) |
解構賦值 const {method} = obj | method() 時 this 為 undefined | 保留物件引用 obj.method() 或 const bound = obj.method.bind(obj) |
function Person(name) {
const _this = this; // 捕獲外層 this
this.name = name;
this.sayLater = function() {
setTimeout(function() {
console.log(_this.name); // 正確
}, 1000);
};
}
ES6 class、私有欄位 #field、extends/super 已成標準,**新專案首選 Class**。維護 ES5 代碼時,掌握「建構函式 + 原型 + 閉包私有 + 寄生組合繼承」模式,並謹記 this 只在呼叫時決定,善用箭頭函數與 bind 固定上下文。