利用 JavaScript 物件的 prototype 性質 (property) 可以避免浪費記憶體空間的問題,這是說,將方法定義移出建構子定義之中,稍後再以物件用 prototype 性質定義該方法,如下例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | function run() { var c = document.getElementById( "content" ); var n = document.createElement( "p" ); var demo = new Demo( "John" , "Mary" ); n.appendChild(document.createTextNode(demo.showMessage())); c.appendChild(n); } function Demo(a, b) { this .a = a; this .b = b; } Demo.prototype.showMessage = function () { return "Demo is " + this .a + ", " + this .b; } /* 《程式語言教學誌》的範例程式 檔名:run38.js 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2010 年 11 月 */ |
利用以下的 HTML 文件載入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | < html > < head > < title >JavaScript Demo</ title > < script src = "run38.js" type = "text/javascript" ></ script > </ head > < body > < input id = "b" type = "text" value = "" > < input id = "b" type = "button" value = "RUN" onclick = "run();" > < div id = "content" ></ div > </ body > </ html > <!-- 《程式語言教學誌》的範例程式 檔名:jsexample41.html 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2010 年 11 月 --> |
瀏覽器 (broswer) 開啟後執行,如下

第 15 行到第 17 行
15 16 17 | Demo.prototype.showMessage = function () { return "Demo is " + this .a + ", " + this .b; } |
這裡示範 Demo 物件以 prototype 性質另外定義 showMessage() 方法。
因此, Demo 物件的建構子
11 12 13 14 | function Demo(a, b) { this .a = a; this .b = b; } |
僅定義 a 與 b 兩個屬性。
中英文術語對照 | |
---|---|
物件 | object |
建構子 | constructor |
屬性 | attribute |
方法 | method |
性質 | property |
瀏覽器 | broswer |
沒有留言:
張貼留言