使用js的callback对象方法
using js callback with object methods
在使用回调模式为控制面板制作模板时,我对代码在调用时执行的确切方式产生了兴趣。在尝试了各种各样的东西之后,我偶然发现了我不理解的模式。代码如下。我不太明白为什么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();
相关文章:
- 从 javascript 中的对象方法返回一个对象
- 在Javascript中调用对象方法时不是函数类型错误
- Java Script将对象方法映射到数组中的对象
- 将数据从promise then方法传递到对象方法
- 设置显示后Flash对象方法不可用:无
- 通过引用Javascript中的另一个函数来传递对象方法
- Javascript库对象方法声明
- JavaScript对象范围-在对象方法中使用对象变量
- jQuery:如何使用文字对象方法中的方法来获取全局变量
- Javascript 对象方法不更新变量
- setInterval 只在对象方法上运行一次
- 对象方法中函数中的上下文
- 用JavaScript编写对象方法的最佳方式是什么
- 使用回调处理程序调用函数内部的父对象方法
- 从Javascript中的对象方法中访问全局变量
- 将此(对象)传递到一个对象方法嵌套方法中
- 为什么我得到“;不是函数错误”;对于我的对象方法
- 带有回调的Javascript对象方法中的递归
- 更正Node.js异步管道中的对象方法调用
- 如何在对象方法上调用requestAnimFrame