JavaScript 共有六種資料型別:一種類型複雜的物件(reference type),以及五種簡單的原始型別(primitive type):Number、String、Boolean、Undefined 與 Null。其中,最核心的正是物件型別。要特別注意的是,簡單型別是不可變的,而物件型別則是可變的。
一個物件是一組以名—值對(name-value pairs)形式儲存的無序清單,清單中的每一項稱為屬性(property),若該項為函式則稱為方法(method)。
var myFirstObject = {
firstName: "Richard",
favoriteAuthor: "Conrad"
};
可以把物件想成一個清單,每項都以名—值對存放。上例中屬性名為 firstName 與 favoriteAuthor,對應值則是 Richard 與 Conrad。屬性名可以是字串或數字,但若以數字作為屬性名,就必須用中括號記法來取值:
var ageGroup = {30: "Children", 100: "Very Old"};
console.log(ageGroup.30); // 報錯
console.log(ageGroup["30"]); // Children
// 建議盡量避免使用數字作為屬性名
兩者最大的不同在於儲存方式:引用型別是按引用儲存,不會像原始型別那樣直接把值存在變數裡。
// 原始型別按值儲存 var person = "Kobe"; var anotherPerson = person; // anotherPerson 取得 person 的值 person = "Bryant"; // person 的值改變了 console.log(anotherPerson); // Kobe console.log(person); // Bryant
可見即使把 person 改為 "Bryant",anotherPerson 絲毫不受影響,仍保留原本被賦予的值。相較之下:
var person = {name: "Kobe"};
var anotherPerson = person;
person.name = "Bryant";
console.log(anotherPerson.name); // Bryant
console.log(person.name); // Bryant
這裡把 person 物件複製給 anotherPerson,由於物件中存的是引用而非真正的值,因此改變 person.name 時,anotherPerson 也會反映這個變化。
每個屬性除了自身的名—值對,還含三個特性,預設皆為 true:
• Configurable:該屬性是否可刪除或修改。
• Enumerable:該屬性是否能在 for-in 迴圈中被取得。
• Writable:該屬性是否可修改。
1. 物件字面量——最常用也最簡潔:
var myBooks = {};
var mango = {
color: "yellow",
shape: "round",
sweetness: 8,
howSweetAmI: function () { console.log("Hmm Hmm Good"); }
};
2. 物件建構函式——使用 new 呼叫:
var mango = new Object();
mango.color = "yellow";
mango.shape = "round";
mango.sweetness = 8;
mango.howSweetAmI = function () { console.log("Hmm Hmm Good"); }
若只是臨時儲存資料的簡單物件,上述兩法已足夠。但若程式要大量建立同類物件(例如展示各種水果),每次都重複敲屬性既乏味又難維護。為了解決重複問題,工程師發展出多種模式:
1. 建構函式模式
function Fruit(theColor, theSweetness, theFruitName, theNativeToLand) {
this.color = theColor;
this.sweetness = theSweetness;
this.fruitName = theFruitName;
this.nativeToLand = theNativeToLand;
this.showName = function () { console.log("This is a " + this.fruitName); }
this.nativeTo = function () {
this.nativeToLand.forEach(function (eachCountry) {
console.log("Grown in:" + eachCountry);
});
}
}
var mangoFruit = new Fruit("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
mangoFruit.showName(); // This is a Mango.
mangoFruit.nativeTo();
如此一來,只需修改一處,就能同時更新所有實例,維護性大幅提升。
2. 原型模式
function Fruit () { }
Fruit.prototype.color = "Yellow";
Fruit.prototype.sweetness = 7;
Fruit.prototype.fruitName = "Generic Fruit";
Fruit.prototype.nativeToLand = "USA";
Fruit.prototype.showName = function () { console.log("This is a " + this.fruitName); }
Fruit.prototype.nativeTo = function () { console.log("Grown in:" + this.nativeToLand); }
var mangoFruit = new Fruit();
mangoFruit.showName(); // This is a Generic Fruit
mangoFruit.nativeTo(); // Grown in:USA
需要牢記幾個要點:可繼承的屬性定義在 prototype 上;屬於自身的屬性直接定義在物件本身。存取屬性用 object.property,呼叫方法用 object.method()。
點記法:
var book = {title: "Ways to Go", pages: 280, bookMark1: "Page 20"};
console.log(book.title); // Ways to Go
console.log(book.pages); // 280
中括號記法:
console.log(book["title"]); // Ways to Go var bookTitle = "title"; console.log(book[bookTitle]); // Ways to Go console.log(book["bookMark" + 1]); // Page 20
存取不存在的屬性會得到 undefined。
物件同時擁有自身屬性(直接定義在物件上)與繼承屬性(從 prototype 繼承而來)。使用 in 運算子可判斷是否擁有某屬性:
var school = {schoolName: "MIT"};
console.log("schoolName" in school); // true
console.log("schoolType" in school); // false
console.log("toString" in school); // true(繼承自 prototype)
若要確認是否擁有「特定自身屬性」,則使用 hasOwnProperty:
console.log(school.hasOwnProperty("schoolName")); // true
console.log(school.hasOwnProperty("toString")); // false
var school = {schoolName: "MIT", schoolAccredited: true, schoolLocation: "Massachusetts"};
for (var eachItem in school) {
console.log(eachItem); // schoolName, schoolAccredited, schoolLocation
}
從 prototype 繼承而來的屬性通常不可列舉,因此不會出現在 for-in 中;但若是可列舉的繼承屬性,則能被存取到。
使用 delete 運算子刪除屬性。不能刪除繼承屬性,也不能刪除 Configurable 為 false 的屬性。要刪除繼承屬性,須從定義它的 prototype 物件上移除。
var christmasList = {mike: "Book", jason: "sweater"};
delete christmasList.mike; // 刪除 mike
for (var people in christmasList) {
console.log(people); // 只剩 jason
}
delete christmasList.toString; // 回傳 true,但 toString 是繼承屬性,不會被刪除
要在 HTTP 中傳遞物件或轉為字串,必須先序列化,可用 JSON.stringify;反之用 JSON.parse 反序列化。
var christmasList = {mike: "Book", jason: "sweater", chelsea: "iPad"};
JSON.stringify(christmasList);
JSON.stringify(christmasList, null, 4); // 加上縮排格式化
var christmasListStr = '{"mike":"Book","jason":"sweater","chelsea":"iPad"}';
var christmasListObj = JSON.parse(christmasListStr);
console.log(christmasListObj.mike); // Book
掌握這些物件核心概念,是邁向進階 JavaScript 開發的重要基礎。想更深入者可參考《JavaScript 權威指南》第六章。