JavaScript设计模式之原型模式(Prototype Pattern)

Gof中对原型模式的解释是基于一个存在对象(模板),通过克隆的方式来创建新对象。

我们知道在JS中没有Class的抽象,一切皆对象,而实际上,JS中存在另一个重要的抽象 Type和Prototype。

照葫芦画瓢,葫芦就是原型,瓢就是Type。这本身就是原型模式的真正体现。


在JS里,ECMAScript 5 standard已经很好的实现了原型模式,通过一个简单的Object.create调用,就可以轻松的基于一个对象创建新的对象。

例子如下。

var myCar = {
  name: "Ford Escort",
  drive: function () {
    console.log( "Weeee. I'm driving!" );
  },
  panic: function () {
    console.log( "Wait. How do you stop this thing?" );
  }
};
// Use Object.create to instantiate a new car
var yourCar = Object.create( myCar );
// Now we can see that one is a prototype of the other
console.log( yourCar.name );

使用Object.Create()的第二个参数,我们可以初始化一些对象属性,例如:

var vehicle = {
  getModel: function () {
  console.log( "The model of this vehicle is.." + this.model );
  }
};
var car = Object.create(vehicle, {
  "id": {
    value: MY_GLOBAL.nextId(),
    // writable:false, configurable:false by default
    enumerable: true
  },
  "model": {
    value: "Ford",
    enumerable: true
  }
});



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值