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