本篇體驗通過硬編碼、工廠模式、建構函式來建立JavaScript物件。
□ 通過硬編碼建立JavaScript物件
當需要建立一個JavaScript物件時,我們可能這樣寫:
var person = {firstName: "Darren",
lastName: "Ji",
getFullName: function() {return this.firstName + " " + this.lastName;}};
如果需要建立2個結構相同的物件,我們可能這樣寫:
var person = {firstName: "Darren",
lastName: "Ji",
getFullName: function() {return this.firstName + " " + this.lastName;}};var person2 = {firstName: "Darren2",
lastName: "Ji2",
getFullName: function () {return this.firstName + " " + this.lastName;}};
□ 通過工廠模式建立JavaScript物件
但實際上,還可以通過工廠模式來建立JavaScript物件。
var person1 = createPerson("Darren1", "Ji1"),person2 = createPerson("Darren2", "Ji2");function createPerson(firstName, lastName) {return {
firstName: firstName,lastName: lastName,getFullName: function() {return this.firstName + " " + this.lastName;}};}
繼續在createPerson函式中增加一個方法,並呼叫。
var person1 = createPerson("Darren1", "Ji1"),person2 = createPerson("Darren2", "Ji2");alert(person1.greet(person2));function createPerson(firstName, lastName) {return {
firstName: firstName,lastName: lastName,getFullName: function() {return this.firstName + " " + this.lastName;},greet: function(person) {if (typeof person.getFullName !== "undefined") {return "hello, " + person.getFullName();} else {
return "are u here?";}}};}
輸出結果:hello, Darren2 Ji2
如果person1.greet方法的實參為匿名物件,如下:
alert(person1.greet({}));
輸出結果:are u here?
□ 通過建構函式建立JavaScript物件
就像通過var arr = new Array()建立陣列物件,通過var date = new Date()建立日期物件,JavaScript允許我們建立自定義資料型別。
var Person = function(firstName, lastName) {this.firstName = firstName;
this.lastName = lastName;
this.getFullName = function() {
return this.firstName + " " + this.lastName;};this.greet = function(person) {
if (person instanceof Person) {
return "hello, " + person.getFullName();} else {
return "are u here?";}};};var person1 = new Person("Darren", "Ji"),person2 = new Person("Jack", "Zhang");alert(person1.greet({getFullName: "this is string"
}));
輸出結果:are u here?
○ 變數Peson的第一個字母大寫,這是一個慣例,表示Peson是自定義資料型別
○ this表示Person物件
○ instanceof用來判斷變數是否是某種資料型別
○ 通過new來建立資料型別物件,new關鍵字不可獲取,否則,在本例中this會指向window
○ 因為person1.greet()的實參不是Peson型別,所以輸出了are u here?
如果把最後一行程式碼改成:
alert(person1.greet(person2));
輸出結果:hello, Jack Zhang
但這裡還有一點小問題:getFullName和greet可看作是物件,每次通過new建立Peson物件時,相當於在記憶體上建立了2份的Peson物件,以及2份的getFullName和greet物件,這增加了記憶體開銷。是否可以讓getFullName和greet放到一個公共的地方,然後每個Peson物件都可以引用他們呢?--prototype屬性此時就可以用上了!
var Person = function(firstName, lastName) {this.firstName = firstName;
this.lastName = lastName;
};Person.prototype.getFullName = function () {return this.firstName + " " + this.lastName;};Person.prototype.greet = function (person) {if (person instanceof Person) {
return "hello, " + person.getFullName();} else {
return "are u here?";}};var person1 = new Person("Darren", "Ji"),person2 = new Person("Jack", "Zhang");alert(person1.greet(person2));
輸出結果:hello, Jack Zhang
以上,在Peson的prototype屬性上定義的方法,能夠被每個Peson物件共享,這從一定程度上減少了記憶體開銷。
“JavaScript進階系列”包括: