0

If I have something like this:

Foo = function  (bar_) {
    this.bar = bar_;
    this.run = function() {
    cron.schedule('*/5 * * * * *', function() {
       console.log(/*this.bar?*/);
    });
}

var myvar = new Foo("mybar");
myvar.run();

How can I set the cron to print out this.bar's value at the time this.run is called? I've tried with this.bar and it returns undefined.

Bren
  • 3,516
  • 11
  • 41
  • 73

1 Answers1

1

You could try this:

Foo = function  (bar_) {
this.bar = bar_;
var that = this
this.run = function() {
   cron.schedule('*/5 * * * * *', function() {
      console.log(that.bar);
   });
}

var myvar = new Foo("mybar");
myvar.run();

The explanation comes as follow: this is a reference to the instance of class Foo, but it's also the default reference for any instantiated object to itself.

So, inside of cron.schedule call, this points to cron and not to Foo. Copying this to that before , and using that inside cron.shcedule gives you the correct object ("this") you're looking for

mtsdev
  • 613
  • 5
  • 11