0

我有一个变量说 var tree。我想在两个文件中使用这个变量,比如 a.js 和 b.js。这两个文件都改变了变量树的状态。我想在其他文件中访问该变量并改变状态。它是如何可能的??

4

1 回答 1

1

There are more elegant ways of doing it, as described in the question linked in the comments, but the simplest way is to define a RequireJS module with an object literal to hold the shared state:

define('sharedstuff', [], {tree: "original value"});

And then from other module you can require it:

require(['sharedstuff'], function(sharedstuff) {
    sharedstuff.tree = "new value";
};

And if from yet another module you require it, RequireJS will not reload a fresh copy but will instead give you the already loaded version with your shared value populated:

require(['sharedstuff'], function(sharedstuff) {
    console.log(sharedstuff.tree) // should be "new value"
};
于 2013-07-03T14:04:02.663 回答