Javascript文件中的共享变量返回过时值

时间:2018-06-19 04:24:48

标签: javascript

我有2个javascript文件。我想创建一个共享的变量,它将在文件1中创建,但可以在第二个文件中使用。共享变量用一定值初始化,但随后用文件1中的其他值更新。由于在文件1中更新变量后调用文件2,我希望它具有最新值,但它总是让我过时值。这就是我的尝试。

档案1

var myVar ='100';

//assume updateMyVar function exists which will return a callback with the value that needs to be updated

updateMyVar('someKey', function(result)
{
//let's assume the result came back as someValue
    console.log("inside callback " + result);
    myVar = result;

});

module.exports.myvar = myvar;

文件2

var file1 =require('./file1');
var myvar = file1.myvar;

//expecting myvar to be someValue instead of 100
console.log(myvar);

2 个答案:

答案 0 :(得分:3)

最好为它定义一个getter

file1.js

const getMyVar = ()=>{
    return myVar;
}

module.exports.getMyVar = getMyVar;

<强> file2.js

var {getMyVar} =require('./file1');
console.log(getMyVar());

截至目前,

module.exports.myvar = myvar;

此语句提供具有当前值myvar的一次性绑定; 因此,每次在更新后获取它都没有更新的值。

答案 1 :(得分:0)

希望这会有所帮助:

// Use some kind of Module pattern to achieve this in a proper manner.
const X_MODULE = (() => { // Anonymous function
    this.myVar = 100;

    updateMyVar('someKey', (result) => {
        //let's assume the result came back as someValue
        console.log("inside callback " + result);
        this.myVar = result;
    });
    return this;
})(); // IIFE -> Immediately Invoked Function Expression.

module.exports = X_MODULE;

// OR make use of one of the OOPs Singleton Class Pattern
class X_MODULE {

    constructor() {
        this._myVar = 100;

        // I've kept this call just for demonstration purpose.
        updateMyVar('someKey', (result) => {
            //let's assume the result came back as someValue
            console.log("inside callback " + result);
            this._myVar = result;
        });
    }

    get myVar() {
        return this._myVar;
    }
}
module.exports = new X_MODULE(); // Singleton Pattern: will have only one instance throughout the app lifecycle.

这两种方法都会给你完全相同的结果。