使用js回调和对象方法

时间:2015-07-30 00:33:14

标签: javascript object methods callback

在使用回调模式处理控制面板的模板时,我对代码在调用时获取执行的确切方式感兴趣。在尝试了各种各样的事情之后,我偶然发现了一些我不明白的模式。代码如下。我无法理解为什么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');

1 个答案:

答案 0 :(得分:0)

您在代码中调用了两次:

require('dependancyX')