1.闭包和面向对象设计
1.1闭包实现
var extent = function(){
var value = 0;
return {
call:function(){
value++;
console.log(value)
}
}
}
var extent = extent()
extent.call() // 输出1
extent.call() // 输出2
extent.call() // 输出3
1.2面向对象
var extent = {
value:0,
call:function(){
this.value++;
console.log(this.value)
}
}
extent.call() // 输出1
extent.call() // 输出2
extent.call() // 输出3
1.3或者面向对象
var Extent = function(){
this.value = 0
}
Extent.prototype.call = function(){
this.value++;
console.log(this.value)
}
var extent = new Extent()
extent.call() // 输出1
extent.call() // 输出2
extent.call() // 输出3
2.命令模式
2.1使用面向对象方式实现
<button id="execute">点击我执行命令</button>
<button id="undo">点击我执行命令</button>
<script>
var Tv = {
open:function(){
console.log('打开电视机')
},
close:function(){
console.log('关闭电视机')
}
}
var OpenTvCommand = function(receive){
this.receive = receive;
}
OpenTvCommand.prototype.execute = function(){
this.receive.open()
}
OpenTvCommand.prototype.undo = function(){
this.receive.close()
}
var setcommand = function(command) {
document.getElementById('execute').onclick = function(){
command.execute()
}
document.getElementById('undo').onclick = function(){
command.undo()
}
}
setcommand(new OpenTvCommand(Tv))
</script>
2.2使用闭包方式实现
<button id="execute">点击我执行命令</button>
<button id="undo">点击我执行命令</button>
<script>
var Tv = {
open:function(){
console.log('打开电视机')
},
close:function(){
console.log('关闭电视机')
}
}
var createCommand = function(receive){
var execute = function(){
return receive.open()
}
var undo = function(){
return receive.close()
}
return {
execute:execute,
undo:undo
}
}
var setcommand = function(command) {
document.getElementById('execute').onclick = function(){
command.execute()
}
document.getElementById('undo').onclick = function(){
command.undo()
}
}
setcommand( createCommand(Tv) )
</script>