Bren Bren - 1 month ago 5
Node.js Question

How to pass information from a member variable to a member method while using node-cron?

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
.

Answer

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

Comments