javascript设计模式-原型模式(prototype pattern)

简单的说就是基于一个创建好的对象作为一个模板(原型)来创建其他的对象。

通过Object.create()实现方式

// 1) Object.create(prototypeObject)
var someCar = {
    drive: function() {},
    name: 'Mazda 3' 
};
var anotherCar = Object.create(someCar);


// 2) Object.create(prototypeObject, otherProperties)
var vehicle = {
    getModel: function () {
        console. log('The model of this vehicle is..' + this.model);
    }
};
var car = Object. create(vehicle, {
    'id' : {
        value: MY_GLOBAL.nextId(),
        enumerable: true
    },
    'model' : {
        value: 'Ford' ,
        enumerable: true
    }
});

备选实现方式

var vehiclePrototype = {
    init: function (carModel) {
        this.model = carModel;
    },
    getModel: function () {
        console. log('The model of this vehicle is..' + this. model);
    }
};
function vehicle(model) {
    // 创建构造函数
    function F() {};
    // 通过设置构造函数的原型属性来连接原型对象
    F.prototype = vehiclePrototype;
    // 使用构造函数创建对象
    var f = new F();
    // 初始化对象,这里不是原型设计模式部分
    f.init(model);
    // 返回创建好的对象 
    return f;
}
var car = vehicle('Ford Escort');
car.getModel();

不包含初始化代码的最简实现

var beget = (function () {
    function F() {}
    return function (proto) {
        F.prototype = proto;
        return new F();
    };
})();


你可能感兴趣的:(javascript设计模式-原型模式(prototype pattern))