在 JavaScript 中,建構函式 ( Constructor Function ) 是一種建立自訂物件的常用方式。透過 this 關鍵字與 prototype 屬性,我們可以快速定義物件的屬性與方法,並產生多個具備相同行為與特性的實例 ( instance )。
本篇文章將透過一個簡單的範例,帶你理解建構函式的基本用法、原型方法的設計方式,以及與 ES6 class 語法的對比。
範例一
以下是一個名為 Tryobj 的建構函式。物件實例會接收一個最大值 n 與 times,並透過方法隨機生成 1 到 n 之間的數字。
程式碼ㄧ
<script type="text/javascript">
function Tryobj(n, times) { // 定義屬性 ( 為了節省記憶體,我們將方法定義在建構函式的 prototype 上。)
this.n = n; // 設定最大數值範圍
this.times = times; // 初始化 times
}
//原型方法:產生隨機值並輸出
Tryobj.prototype.actions = function() {
const result = Math.floor(Math.random() * this.n+1);
console.log(`第${this.times}次隨機值:${result} (n 值:${this.n})\n`);
};
// 原型方法:延遲執行 actions,模擬等待效果
Tryobj.prototype.act2 = function() {
setTimeout(this.actions.bind(this),1200);
};
// 實例化並執行
const testObj = new Tryobj(100,1);
testObj.act2();
</script>
現代化:ES6 class 語法糖
雖然建構函式和 prototype 是 JavaScript 物件建立的底層機制,但在 ES6(2015)之後,我們通常使用 class 語法來實現相同的目的。它語法更簡潔、更接近傳統物件導向語言,但其背後運作的原理仍然是建構函式和原型(prototype)機制。
範例二
以下是使用 ES6 class 實現的範例
程式碼二
<script type="text/javascript">
class TryobjClass1 {
// 替代建構函式(Constructor Function)
constructor(n, times) {
this.n = n;
this.times = times;
}
//直接定義方法,會自動掛載到 class 的 prototype 上
actions() {
const result = Math.floor(Math.random() * this.n+1);
console.log(`第${this.times}次隨機值:${result} (n 值:${this.n})\n`);
}
act2() {
setTimeout(this.actions.bind(this),1200);
}
}
// 實例化並執行
const testObj = new TryobjClass1(100,1);
testObj.act2();
</script>
結論:建構函式搭配 prototype 是 JavaScript 中建立可重複使用物件的核心技巧之一。透過本篇範例,你應該可以理解:
- 如何將共用方法掛在原型上,節省記憶體空間。
- 現代化:ES6 class 語法只是建構函式與原型繼承的語法糖,底層機制並未改變。
沒有留言:
張貼留言
請注意 : 您的留言發佈成功 , 需經審核後 , 才能決定是否回覆 . 謝謝 !!