首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在对象方法中使用js回调

在对象方法中使用js回调
EN

Stack Overflow用户
提问于 2015-07-30 08:33:14
回答 1查看 25关注 0票数 0

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

代码语言:javascript
复制
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');
EN

回答 1

Stack Overflow用户

发布于 2015-07-30 09:09:50

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

代码语言:javascript
复制
controlPanel.stuff(function(){console.log('and this stuff is awesome!')});

controlPanel.stuff();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31713407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档