js設計模式之Constructor(構造器)


說明:最近正在看Addy Osmani寫的《JavaScript設計模式》這本書,故記一下讀書筆記與大家分享。本文的內容基本上都出自那本書,如果覺得不錯可以去買一本看看。

9.1Constructor(構造器)模式

Object構造器用於創建特定類型的對象——准備好對象以備使用,同時接受構造器可以使用的參數,以在第一次創建對象時,設置成員屬性和方法的值。

9.1.1 創建對象

    var newObject=new Object();
    //var newObject={};
    //1.直接設置屬性
    newObject.hello1="hello 1";
    console.log(newObject.hello1)
    //2.中括號法
    newObject["hello2"]="hello 2";
    console.log(newObject.hello2);
    //3 設置對象屬性,並修改現有屬性的特性
    Object.defineProperty(newObject,"hello3",{
        value:"hello 3",
        writable:true,
        enumerable:true,
        configurable:true
    });
    console.log(newObject.hello3);
    //3的模板,添加多個屬性時可減少代碼量
    var defineProp=function(obj,key,value){
        //config.value=value; 書中此處的代碼用了會報錯:config is not defined,故修改了此處代碼。
        var config = {
            value: value,
            writable: true,
            enumerable: true,
            configurable: true
        };
        Object.defineProperty(obj,key,config);
    };
    var person=Object.create(null);
    defineProp(person,"language","js");
    defineProp(person,"birthday","1989");
    defineProp(person,"hasBeard",false);
    //遍歷打印person的所有屬性
    for (var obj in person) {
        console.log(obj + ' : ' + person[obj]);
    }
    //4 設置對象屬性的另一種方法
    Object.defineProperties(newObject,{
        "someKey":{
            value:"hello world",
            writable:true
        },
        "anotherKey":{
            value:"foo bar",
            writable:false
        }
    });
    //此處打印用for循環為空,原因不明
    console.log(newObject.someKey);
    console.log(newObject.anotherKey);
    //5 繼承,子類會獲得父類的屬性
    var driver=Object.create(person);
    defineProp(driver,"topSpeed","100mph");
    for (var obj in driver) {
        console.log(obj + ' : ' + driver[obj]);
    }

 9.1.2基本Constructor(構造器)

    //簡單的構造器模式
    function Car(model,year,miles){
        this.model=model;
        this.year=year;
        this.miles=miles;
        this.toString=function(){
            return this.model+" has done "+this.miles+" miles";
        }
    }

 

問題:1.使繼承變得困難

2.toString()這樣的函數是為每個使用Car構造器創建的新對象而分別重新定義的,這不是最理想的,因為這種函數應該在所有的car類型實例之間共享(感覺像是java中的靜態方法)

9.1.3帶原型的Constructor(構造器)

javascript中有一個名為prototype的屬性,調用js構造器創建一個對象后,新對象就會具有構造器原型的所有屬性。通過這種方式,可以創建多個car對象,並訪問相同的原型。這樣toString()這樣的方法就能夠在所有Car對象之間共享。

//帶原型的構造器
    function Car(model,year,miles){
        this.model=model;
        this.year=year;
        this.miles=miles;
    };
    Car.prototype.toString=function(){
        return this.model+" has done "+this.miles+" miles";
    };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM