您的位置:首页 > Web前端 > JavaScript

javascript 几种常见设计模式

2016-03-29 21:11 666 查看
<body>
<button id="show">show</button>
<button id="hide">hide</button>
<hr>
<button id="factoryShow">show</button>
<button id="factoryHide">hide</button>
<hr>
<button id="thisShow">show</button>
<button id="thisHide">hide</button>
<hr>
<button id="mixShow">show</button>
<button id="mixHide">hide</button>

<script>
window.onload = function (argument) {
//单例
function layer(){
function show(){
console.log('show');
}

function hide(){
console.log('hide');
}

return {
hide:hide,
show:show
}
};
var lio = layer();
document.getElementById('show').addEventListener('click',function(){
lio.show();
},false);
document.getElementById('hide').addEventListener('click',function(){
lio.hide();
},false);

//工厂模式
function factory(){
var factory = {};
factory['show'] = function(){
console.log('factoryshow');
}
factory.hide = function(){
console.log('factoryhide');
}
return factory;
}
var gongchang = factory();
document.getElementById('factoryShow').addEventListener('click',function(){
gongchang.show();
},false);
document.getElementById('factoryHide').addEventListener('click',function(){
gongchang.hide();
},false);

//构造函数模式
function construct(){
this.show = function(){
console.log('thisshow');
}
this.hide = function(){
console.log('thishide');
}
}
var construct = new construct();
document.getElementById('thisShow').addEventListener('click',function(){
construct.show();
},false);
document.getElementById('thisHide').addEventListener('click',function(){
construct.hide();
},false);

//混合模式
function mix(){
this.show = function(){
console.log('thisshow');
}
this.hide = function(){
console.log('thishide');
}
}
mix.prototype.prototypeShow = function(first_argument) {
console.log('prototypeshow');
};
var mix = new mix();
document.getElementById('mixShow').addEventListener('click',function(){
mix.prototypeShow();
},false);
document.getElementById('mixShow').addEventListener('click',function(){
mix.show();
},false);
document.getElementById('mixHide').addEventListener('click',function(){
mix.hide();
},false);

}

</script>

</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript