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();
    };
})();


转载于:https://my.oschina.net/osmos/blog/386809

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值