简体   繁体   English

node.js 变量范围

[英]node.js variable scopes

I havethe following exported object:我有以下导出的对象:

module.exports = {
    value: 0,

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

How can I access value from that setInterval function?如何从该 setInterval 函数访问value Thanks in advance.提前致谢。

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 :或者,如果将setTimeout调用的函数绑定到this ,则可以使用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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM