NodeJS:Early require无法访问对象字段

时间:2016-08-07 13:00:19

标签: javascript node.js require

我在访问文件顶部需要/导入的对象中的字段时遇到问题,但是在代码中稍后再次导入对象时可以访问该字段。

我举了一个例子来说明我的意思:[Execute code on CodingGround]

main.js

var ClassA = require('./ClassA');

ClassA.init();

ClassA.js

var ClassB = require('./ClassB');

var ClassA = function() {};

ClassA.init = function() {
    // Define a variable in ClassA
    this.myVar = 'My Value';

    // Create an instance of ClassB, and try to print the defined variable
    var myClass = new ClassB();
    myClass.printMyVar();
};

module.exports = ClassA;

ClassB.js

var ClassA = require('./ClassA');

var ClassB = function() {};

ClassB.prototype.printMyVar = function() {
    // Print the variable (not working)
    console.log('My Var: ' + ClassA.myVar);

    // Require ClassA again
    ClassA = require('./ClassA');

    // Print the variable again (working)
    console.log('My Var (again): ' + ClassA.myVar);
};

module.exports = ClassB;

执行main.js时,我得到以下输出:

My Var: undefined
My Var (again): My Value

为什么第一行显示变量未定义,为什么在再次要求/导入对象后它会正确显示变量?

这是由循环依赖引起的,如果是,我将来如何避免这个问题?

1 个答案:

答案 0 :(得分:1)

这是in the NodeJS modules "cycle" topic所描述的情况。解决方案似乎是扩充 exports对象,而不是替换,如果存在循环依赖关系。

以下是他们的示例,经过修改后显示,当b稍后检查a.done 时,它会看到正确的值:

a.js:

console.log('a starting');
exports.done = false;
const b = require('./b.js');
console.log('in a, b.done = %j', b.done);
exports.done = true;
console.log('a done');

b.js:

console.log('b starting');
exports.done = false;
const a = require('./a.js');
console.log('in b, a.done = %j', a.done);
exports.done = true;
exports.check = function() {
    console.log('in b\'s check function, a.done = %j', a.done);
};
console.log('b done');

main.js:

console.log('main starting');
const a = require('./a.js');
const b = require('./b.js');
console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
b.check();

输出结果为:

main starting
a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
in main, a.done=true, b.done=true
in b's check function, a.done = true