面向对象版本:预先植入的命令接收者被当成对象的属性保存起来
var Tv = {
open: function() {
console.log('open tv');
},
close: function() {
console.log('close tv');
}
};
var OpenTvCommand = function(receiver) {
this.receiver = receiver;
}
OpenTvCommand.prototype.excute = function() {
this.receiver.open();
}
OpenTvCommand.prototype.undo = function() {
this.receiver.close();
}
var setCommand = function(command) {
document.querySelector('#excute').onclick = function() {
command.excute();
};
document.querySelector('#undo').onclick = function() {
command.undo();
};
};
setCommand(new OpenTvCommand(Tv));
闭包版本:命令接收者被封闭在闭包形成的环境中
var Tv = {
open: function() {
console.log('open tv');
},
close: function() {
console.log('close tv');
}
};
var createCommand = function(receiver) {
var excute = function() {
receiver.open();
};
var undo = function() {
receiver.close();
};
return {
excute: excute,
undo: undo,
};
}
var setCommand = function(command) {
document.querySelector('#excute').onclick = function() {
command.excute();
};
document.querySelector('#undo').onclick = function() {
command.undo();
};
};
setCommand(createCommand(Tv));
网友评论