面向?qū)ο蟀姹荆侯A先植入的命令接收者被當成對象的屬性保存起來
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));
閉包版本:命令接收者被封閉在閉包形成的環(huán)境中
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));
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者