设计模式:prototype(原型)模式

创建型设计模式

Prototype模式是基于原型继承的模式,可以在其中创建对象,作为其他对象的原型。prototype对象本身实际上是用作构造函数创建每个对象的蓝图。

简单实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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();
1
2
3
4
5
6
7
var beget = (function(){
function F(){}
return function (proto){
F.prototype = proto;
return new F();
}
})();