我创建了一个执行操作的worker对象。为了防止它同时执行两个操作,有一个就绪标志,表示操作已完成,工作人员已为下一个操作做好准备...如下面的代码...
var worker = {
readyFlag:1,
ready: function(){
console.log('ready');
this.readyFlag = 1;
},
working: function(){
console.log('working');
this.readyFlag = 0;
},
work: function () {
console.log(this.readyFlag);
if(this.readyFlag == 1){
this.working();
doTheWork(this.ready);
}
},
};
function doTheWork(callback){
// do the work
console.log('I am executing some work');
callback();
}
worker.work();
worker.work();
问题是,它第一次运行ok,并且它将标志设置回准备好......但由于某种原因它将标志设置回工作状态,即使没有调用.working()函数和控制台。日志不会显示它再次正常工作..
请注意,worker.work()被调用两次,但是第二次,它将不会执行,因为该标志设置为0,即使回调函数应该将其设置为1.发生了什么?
答案 0 :(得分:0)
使用此代码代替您的代码,因为当调用ready
方法时,它在全局上下文中执行(而不是在对象本身中),并将readyFlag
属性设置为全局对象。
work: function () {
console.log(this.readyFlag);
if(this.readyFlag == 1){
this.working();
doTheWork(this.ready.bind(this);
}
},