1、构造函数模式
function Animal(name, color){
this.name = name;
this.color = color;
this.getName = function(){
return this.name;
}
}
var cat = new Animal('狗', '黑色');
console.log( cat.getName() );
2、工厂模式
function Animal(opts){
var obj = new Object();
obj.name = opts.name;
obj.color = opts.color;
obj.getInfo = function(){
return '名称:'+obj.name +', 颜色:'+ obj.color;
}
return obj;
}
var cat = Animal({name: '藏獒', color: '灰褐色'});
cat.getInfo();
3、单例模式
var Single = (function(){
var instance;
function init() {
return {
};
}
return {
getInstance:function(){
if(!instance){
instance = init();
}
return instance;
}
}
})();
var obj1 = Single.getInstance();
var obj2 = Single.getInstance();
console.log(obj1 === obj2);
4、发布订阅模式
var EventCenter = (function(){
var events = {};
function on(evt, handler){
events[evt] = events[evt] || [];
events[evt].push({
handler:handler
})
}
function fire(evt, arg){
if(!events[evt]){
return
}
for(var i=0; i < events[evt].length; i++){
events[evt][i].handler(arg);
}
}
function off(evt){
delete events[evt];
}
return {
on:on,
fire:fire,
off:off
}
}());
var number = 1;
EventCenter.on('click', function(data){
console.log('click 事件' + data + number++ +'次');
});
EventCenter.off('click');
EventCenter.on('click', function(data){
console.log('click 事件' + data + number++ +'次');
});
EventCenter.fire('click', '绑定');
5 、模块模式
var Car = (function(){
var name = '兰博基尼';
function sayName(){
console.log( name );
}
function getColor(name){
console.log( name );
}
return {
name: sayName,
color: getColor
}
})();
Car.name();
Car.color('红色');
6、混合模式
function Animal(name, color){
this.name = name;
this.color = color;
console.log( this.name + this.color)
}
Animal.prototype.getInfo = function(){
console.log('名称:'+ this.name);
}
function largeCat(name, color){
Animal.call(null, name, color);
this.color = color;
}
largeCat.prototype = create(Animal.prototype);
function create (parentObj){
function F(){}
F.prototype = parentObj;
return new F();
};
largeCat.prototype.getColor = function(){
return this.color;
}
var cat = new largeCat("Persian", "白色");
console.log( cat )