javascript建立對象總結(javascript進階程式設計)

來源:互聯網
上載者:User

標籤:javascript

1.原廠模式
這種模式抽象建立具體對象的過程,用函數封裝特定的介面來建立類。
    function createStudent(name) {        var o = new Object();        o.name = name;        o.sayName = function() {            alert(this.name);        };        return o;    }    var student1 = createStudent("Tom");
解決的問題:解決了建立多個相似對象的問題缺點:沒有解決對象識別問題
2.建構函式模式
    function Student(name) {        this.name = name;        this.sayName = function() {            alert(this.name);        };    }    var student1 = new Student("Tom");    var student2 = new Student("Suen");

這種模式建立Student的新執行個體,必須使用new操作符。調用建構函式會經過如下4步驟:(1)建立一個新對象; (2)將建構函式的範圍賦給新對象(因此this就指向了這個新對象); (3)執行建構函式中的代碼(為這個新對象添加屬性) (4)返回新對象

解決的問題:對象識別問題,可以通過constructor屬性和instanceof操作符來檢測物件類型:

        alert(student1.constructor == Student) //true        alert(student2 instanceof Object) //true        alert(student2 instanceof Student) //true

缺點:每個方法都要在每個執行個體上重新建立一遍。比如上面的例子,student1和student2的sayName()不是同一個Function的執行個體,這是不必要的。

3.原型模式

我們建立的每個函數都有一個prototype(原型)屬性,這個屬性是一個指標,指向一個對象,這個對象的用途就是包含所有執行個體共用的屬性和方法。

    function  Student() {    }    Student.prototype.name = "Tom";    Student.prototype.sayName = function(){        alert(this.name);    };    var student1 = new Student("Tom");    var student2 = new Student("Suen");    alert(student1.sayName == student2.sayName); //true

    更簡單的原型文法:    function Student(){    }    Student.prototype = {        constructor : Student,        name : "Tom",        sayName : function() {            alert(this.name);        }    };

解決的問題:所有對象執行個體共用原型中方法,不需要重新建立。
缺點:它省略了為建構函式初始化參數環節,導致所有執行個體在預設情況下都取得相同的屬性值。更嚴重的是原型中的屬性被很多執行個體共用,雖然可以通過執行個體中添加同名屬性解決,但是對於包含參考型別值的屬性來說,問題就比較突出。

4.組合使用建構函式模式和原型模式

建構函式模式用於定義執行個體屬性,而原型模式定義方法和共用的方法。每個執行個體都會有自己的一份執行個體屬性的副本,同時又共用著對方法的引用。

    function Student(name) {        this.name = name;        this.roommates = ["John","Ben"];    }    Student.prototype = {        constructor : Student,        sayName : function() {            alert(this.name);        }    };    var student1 = new Student("Tom");    var student2 = new Student("Suen");    student1.roommates.push("Jim");    alert(student1.roommates); // "John, Ben, Jim"    alert(student2.roommates); // "John, Ben"

這種模式是使用最廣泛,認可度最高的模式。

javascript建立對象總結(javascript進階程式設計)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.