javascript是基於對象的程式設計語言。從window到document,從方法到類,從object到Array都是對象。
先看一下JSON(javascript object notation)對象,JSON是一種指令碼操作時常用的資料交換格式對象,相對於XML來說JSON是一種比較輕量級的格式,在一些 intelligence的IDE中還可以方便的通過點操作JSON對象中的成員。
JSON是一種鍵/值對方式來描述內部成員的格式,其內部成員可以是幾乎任何一種類型的對象,當然也可以是方法、類、數組,也可以是另外一個JSON對象。
var student = {
Name: "張三",
Age: 20,
Hobby: "讀書",
Books: [
{
BookName : "C#" ,
Price : 70
},
{
BookName : "Java" ,
Price : 70
},
{
BookName : "Javascript" ,
Price : 80
}
]
};
上面代碼用JSON對象描述了一個學生的資訊,他有姓名、年齡、愛好、書集等。在訪問該學生對象時,可以通過student變數來操作學生的資訊。
var stuInfo = "姓名:" + student.Name +
",年齡:" + student.Age +
",愛好:" + student.Hobby +
",擁有的書:" +
student.Books[0].BookName + "、" +
student.Books[1].BookName + "、" +
student.Books[2].BookName;
alert(stuInfo);
這樣的操作方式風格和C#也非常相像。以上的代碼是靜態構造出了學生對象,學生對象的結構就確定了。在其它的程式設計語言中一般對象結構一旦確定就不能很方便的進行修改,但是在javascript中的對象結構也可以方便的進行改動。下面為student對象添加一個Introduce方法來做自我介紹。
student.Introduce = function() {
var stuInfo = "姓名:" + this.Name +
",年齡:" + this.Age +
",愛好:" + this.Hobby +
",擁有的書:" +
this.Books[0].BookName + "、" +
this.Books[1].BookName + "、" +
this.Books[2].BookName;
alert(stuInfo)
};
student.Introduce();
student對象原來並沒有Introduce方法,第一次為student.Introduce賦值會在student對象中建立一個新的成員,後面如果再為student.Introduce賦值則會覆蓋上一次所賦的值。當然我們這的值是一個function。也可以用類似索引的方式來新增成員。
student["Introduce"] = function() {
……
};
student.Introduce();
當然添加的成員也可以刪除掉。刪除掉之後則成為undefined,再訪問該成員時則不支援。
delete student.Introduce;
student.Introduce();