# 物件(Object) ###### tags: `NKFW 網頁設計入門` ## 宣告語法 ```javascript! let 物件名稱 = { ...... } ``` ## 介紹 * 在Javascript中,Object是一種與Array相似的datatype。 * Object中可儲存各種datatype的資料,例如integer,string,array,甚至也可以是函數。 ```htmlembedded! let university = { name: "NCU", students: 11938, age: 60, colleges: ["LiberalArts", "Management", "Engineering", "Science", "Hakka"], alertStatement: function() { temp = this.name + " has " + this.students + " students, "; temp += "we have colleges of " + this.colleges + "..."; alert(temp); } } ``` 上圖即是一個object的範例,儲存了名字(name)、學生數(students)、在臺時長(age)、學院別(colleges)等資料,以及一個名為alertStatement的function;我們通常以properties稱呼object中例如name, colleges的這類資料,以method稱呼object中的function。 * 我們可以透過使用「物件名稱.property」來得到物件中的資料,例如: ```htmlembedded! alert("Name: " + university.name); ``` ![](https://i.imgur.com/Rmj722N.png) * 透過「物件名稱.method」來呼叫method,例如: ```htmlembedded! university.alertStatement(); ``` ![](https://i.imgur.com/tQNv3fa.png) * alertStatement()中的「this.propety名稱」功能為取得當前object中的property,若不加入"this"而只有"property名稱",則無法正確執行。 ## Practice :::info 宣告一個object,內容包括一張照片、照片標題、描述、攝影者等資訊,並在裡面撰寫一個函式,作用為在控制臺輸出文句、告訴使用者這張照片的資訊。 完成後,可以試著在主程式中呼叫這些資訊及函式看看。 ::: ## 物件的作用 * 字典(dictionary): ```javascript! let Dictionary { key1: value1, key2: value2, key3: value3, ... }; ``` * 伺服器之間傳送檔案: ![](https://hackmd.io/_uploads/ryxEF4SB3.png) :::info 來源為:https://www.pexels.com/zh-tw/ :::