Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

node.js variable scopes

node.js variable scopes

Problem

I havethe following exported object:

module.exports = {
    value: 0,

    startTimer: function() {
        setInterval(function() {
            value++;
        }, 1000);
    }
}

How can I access value from that setInterval function? Thanks in advance.

Problem courtesy of: john smith

Solution

You can either specify the full path to the value:

module.exports = {
    value: 0,

    startTimer: function() {
        setInterval(function() {
            module.exports.value++;
        }, 1000);
    }
}

Or, if you bind the function called by setTimeout to this, you can use this:

module.exports = {
    value: 0,

    startTimer: function() {
        setInterval(function() {
            this.value++;
        }.bind(this), 1000);
    }
}

This is similar to code like this, which you will see from time to time:

module.exports = {
    value: 0,

    startTimer: function() {
        var self = this;
        setInterval(function() {
            self.value++;
        }, 1000);
    }
}
Solution courtesy of: Michelle Tilley

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

node.js variable scopes

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×