使用js的callback对象方法

using js callback with object methods

本文关键字:对象 方法 callback js 使用      更新时间:2023-09-26

在使用回调模式为控制面板制作模板时,我对代码在调用时执行的确切方式产生了兴趣。在尝试了各种各样的东西之后,我偶然发现了我不理解的模式。代码如下。我不太明白为什么ControlPanel.prototype.stuff()在调用时被调用两次:controlPanel.stuff()谢谢!

var ControlPanel = function() {
this.onClickCallback = null;
this.mouseOverCallback= null;
};
var count = 0;
ControlPanel.prototype.handlers = function(callback) {
console.log('Registered handlers');
this.onClickCallback = callback;
this.mouseOverCallback = callback;
};
ControlPanel.prototype.stuff = function(dosmth){
console.log("cP got stuff!!!! "+ ++count);
if(count===1){dosmth();}};
ControlPanel.prototype.click = function(buttonColor) {
if (!this.onClickCallback || !this.mouseOverCallback) {
   return;
}
if (buttonColor === 'green') {
    this.onClickCallback('Life Is Good or So It Seems');
}
else if (buttonColor === 'red') {
    this.onClickCallback('Be Afraid Be Very Afraid...');
}
if (buttonColor === 'mouse') {
    this.mouseOverCallback( ' The Mouse Is Here...')
}
};
var controlPanel = new ControlPanel();
controlPanel.handlers(function(status) {  //Here is your callback function
//that gets stored in this.smth of controlPanel object
console.log('Received Callback');
console.log(status);
});
//Simple way to define a callback that executes when the controlPanel Object
//  is instantiated
controlPanel.stuff(function(){console.log('and this stuff is awesome!')});
controlPanel.stuff();
controlPanel.click('green');
controlPanel.click('red');
controlPanel.click('mouse');

你在代码中调用了它两次:

controlPanel.stuff(function(){console.log('and this stuff is awesome!')});
controlPanel.stuff();