续谈闭包

承接上篇,我们再来谈谈闭包~~

命令模式与闭包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<button id='execute'>点我吧</button>
<button id='undo'>点我试试</button>
<script src='js/bibao2.js'></script>
</body>
</html>

面向对象形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var tv = {
open: function(){
console.log('打开电视')
},
close: function(){
console.log('关闭电视')
}
};

var OpenTvCommand = function( receiver ){
this.receiver = receiver;
}
OpenTvCommand.prototype.execute = function(){
this.receiver.open();
}
OpenTvCommand.prototype.undo = function(){
this.receiver.close();
}

var setCommand = function( command ){
document.getElementById('execute').onclick=function(){
command.execute();
}
document.getElementById('undo').onclick = function(){
command.undo()
}
};

setCommand( new OpenTvCommand(tv) )

命令模式的意图是把请求封装为对象,从而分离请求的发起者与请求的接收者之间的耦合关系,在命令执行之前,可以预先往命令对象里植入命令的接收者

如果需要往函数对象中预先植入命令的接受者,那么闭包可以完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var tv = {
open: function(){
console.log('打开电视')
},
close: function(){
console.log('关闭电视')
}
};

var createCommand = function( receiver ){
var execute = function(){
return receiver.open();
};
var undo = function(){
return receiver.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) )
文章目录
  1. 1. 命令模式与闭包