定義物件也是使用關鍵字 (keyword) function ,其後空一格接函數的識別字 (identifier) 名稱與小括弧,物件的識別字通常以大寫英文字母開始,小括弧內為可有可無的參數列 (parameter list) ,其後為成對的大括弧,大括弧裡頭放置物件定義。
例如,以下程式定義了 Demo 物件
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; this .showMessage = function () { return "Demo is " + this .a + ", " + this .b; } } /* 《程式語言教學誌》的範例程式 檔名:run37.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 = "run37.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 > <!-- 《程式語言教學誌》的範例程式 檔名:jsexample40.html 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2010 年 11 月 --> |
瀏覽器 (broswer) 開啟後執行,如下

第 11 行到第 18 行
11 12 13 14 15 16 17 18 | function Demo(a, b) { this .a = a; this .b = b; this .showMessage = function () { return "Demo is " + this .a + ", " + this .b; } } |
這裡定義了物件 Demo ,參數 a 與 b 為建立 Demo 所需的資料,底下可以看到有三行運用了 this 關鍵字,其中
12 13 | this .a = a; this .b = b; |
Demo 有屬性 a 與 b ,直接由參數 a 與 b 提供,另外
15 16 17 | this .showMessage = function () { return "Demo is " + this .a + ", " + this .b; } |
showMessage() 為 Demo 的方法,同樣藉由 function 關鍵字定義,這裡, showMessage() 簡單的回傳包含屬性 a 與 b 的字串。
回到看第 5 行
5 | var demo = new Demo( "John" , "Mary" ); |
Demo() 為 Demo 物件的建構子 (constructor) ,建立新的物件變數需要使用關鍵字 new ,表示變數 demo 為一個新的 Demo 物件。
第 7 行
7 | n.appendChild(document.createTextNode(demo.showMessage())); |
此範例示範呼叫自訂 Demo 物件的 showMessage() 方法。
中英文術語對照 | |
---|---|
物件 | object |
屬性 | attribute |
方法 | method |
關鍵字 | keyword |
識別字 | identifier |
參數列 | parameter list |
瀏覽器 | broswer |
建構子 | constructor |
沒有留言:
張貼留言