JavaScript最重要的數據類型就是對象。JavaScript的數據類型分為兩類:一是引用類型,即Object;而是基礎類型,即Number,String,Boolean,Undefined 和 Null。基礎類型和引用類型的區別在于:基礎類型的值是不可變的;引用類型的值是可變的,詳情參見JavaScript(三):基本類型和引用類型的區別。
什么是對象
對象是無序屬性的集合,其屬性可以包含基本值、對象或者函數。嚴格來說,對象是一組沒有特定順序的值。對象的每一個屬性和方法都有一個名字,而這個名字都映射到這個值。
如下是一個簡單的對象:
var myFirstObject = {firstName: "Richard", favoriteAuthor: "Conrad"};
把對象想象成一張列表,其中每一項(對象的屬性或方法)都以鍵值對的方式存儲。
myFirstObject
的屬性是firstName
,favoriteAuthor
;對應的值為"Richard"
,"Conrad"
。
對象的屬性名稱可以是String或者Number,對象屬性名稱如果是Number類型,那么就只能通過綜括號加屬性名的訪問方式訪問。
var ageGroup = {30: "Children", 100:"Very Old"};
console.log(ageGroup.30)
// This will throw an error
// This is how you will access the value of the property 30, to get value "Children"
console.log(ageGroup["30"]); // Children
//It is best to avoid using numbers as property names.
引用類型和基本類型
引用類型和基本類型的重要區別在于:引用類型的保存指針,而不是像基本類型一樣,直接根據變量保存值。如以下兩個例子所示。
一是,基本類型的賦值:
// The primitive data type String is stored as a value
var person = "Kobe";
var anotherPerson = person; // anotherPerson = the value of person
person = "Bryant"; // value of person changed
console.log(anotherPerson); // Kobe
console.log(person); // Bryant
anotherPerson
并不會隨著person
值的變化而變化。
二是引用類型的賦值:
var person = {name: "Kobe"};
var anotherPerson = person;
person.name = "Bryant";
console.log(anotherPerson.name); // Bryant
console.log(person.name); // Bryant
在這里,我們將person
對象賦值給anotherPerson
對象,但是由于person
保存的是指針,因此 我們改變person.name
為"Bryant"
,anotherPerson
的name
屬性也會變成"Bryant"
。
對象的屬性是有特性的
資料來源:
《JavaScript Objects in Detail》http://javascriptissexy.com/javascript-objects-in-detail/