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";
    };

 

原文地址:https://www.cnblogs.com/blackangle/p/3961352.html