0

I have created a worker object that executes actions. To protect it from doing two actions at the same time, there is a ready flag that indicates that an action is completed and worker is ready for the next... as the code below...

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();

The problem is, it runs the first time ok, and it sets the flag back to ready.. but for some reason it sets the flag back to working, even though the .working() function is not called and console.log won't display that it's working again..

Notice that worker.work() is called twice, but on the second time, it won't execute, because the flag is set to 0, even though the callback function is supposed to set it to 1. What's going on?

http://jsbin.com/wijimuriga/edit?html,js,console,output

sigmaxf
  • 7,998
  • 15
  • 65
  • 125

1 Answers1

0

Use this code instead of yours, because when your ready method is called it executes in global context (not in object itself) and set readyFlag property to the global object.

work: function () {
    console.log(this.readyFlag);
    if(this.readyFlag == 1){
        this.working();
        doTheWork(this.ready.bind(this);
    }
},
Dmitriy
  • 3,745
  • 16
  • 24