DIV CSS 佈局教程網

JavaScript 教學:組合使用建構函式與原型模式
編輯:關於JavaScript     

建立自訂型別最常見的方式,就是組合使用建構函式模式與原型模式:建構函式模式用於定義實例屬性,原型模式則用於定義方法與共享屬性。如此一來,每個實例都拥有自己的一份實例屬性副本,同時又共享對方法的參照,最大程度地節省記憶體;此外還支援向建構函式傳遞參數,可謂集兩模式之長。以下程式碼示範了這種寫法:

function Person(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ["Shelby", "Court"];
}
Person.prototype = {
    constructor: Person,
    sayName: function () {
        alert(this.name);
    }
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 29, "Doctor");
person1.friends.push("Van");
alert(person1.friends);    //"Shelby,Count,Van"
alert(person2.friends);    //"Shelby,Count"
alert(person1.friends === person2.friends);    //false
alert(person1.sayName === person2.sayName);    //true

在此例中,實例屬性都在建構函式中定義,而由所有實例共享的 constructor 屬性與 sayName() 方法則定義在原型上。修改 person1.friends 不會影響到 person2.friends,因為它們分別參照不同的陣列。

這種建構函式與原型混成的模式,是目前 ECMAScript 中使用最廣泛、認同度最高的自訂型別建立方式,可說是定義參照型別的一種預設模式。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved