0

My task is very simple I need two workers running.

var taskNum = 0;

function Task() {
  var me = this;
  this.name = '#' + ++taskNum;

  Task.prototype.run = function () {
   console.log(me.name);
   setTimeout(me.run, 1000);
  }
}

var t1 = new Task();
t1.run();
var t2 = new Task();
t2.run();

The output should be 1,2,1,2 but it is: 1 2 1 2 2 2 2 2 2

This could be solved by changing 'Task.prototype.run' to 'this.run'. But can this be fixed by not removing the prototype, because I need it in complex solution?

2 Answers 2

5

That's because you override Task.protoype.run inside the construction function itself, and you set the new version to use the latest me variable.

A more common way to build a class is:

var taskNum = 0;

function Task() {
  this.name = '#' + ++taskNum;
}

Task.prototype.run = function () {
  console.log(this.name);
  setTimeout(Task.prototype.run.bind(this), 1000);
}

var t1 = new Task();
t1.run();
var t2 = new Task();
t2.run();

Sign up to request clarification or add additional context in comments.

6 Comments

don't forget to bind on run!
@DanielA.White - was editing while you commented :-)
Feel free to use setTimeout(this.run.bind(this), 1000)
@dangor - Thanks, I rather be explicit and uber-clear.
@Amit what is bind doing here?
|
1

In JavaScript there is no variable scope like public,private etc . So the object of me gets overridden after executing second new Task() line That's why you are getting that output

You can confirm this by creating two object first then calling run method

var t1 = new Task();
var t2 = new Task();
t1.run();
t2.run();

Now you will get output like 2 2 2 2 2 .....

To solve this issue you can pass tha Task object as parameter in run function like this:

t1.run(t1);

And then change your prototype run function as

Task.prototype.run = function (taskObject) {
    console.log(taskObject.name);
    setTimeout(taskObject.run, 1000);
}

Not tested but most likely it will work

1 Comment

That's not a good idea at all. The purpose of an object is to have properties that can be accessed in it's own context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.