我正在定义一个模块 Foo
并在另一个模块 Bar
中实例化它。我有第三个模块 Other
,我想为它提供与 Bar
创建和修改的相同的 Foo
实例。
define('Foo', [], function() {
var test = function() {
this.foo = 'foo';
};
return test;
});
define('Bar', ['Foo'], function(Foo) {
Foo = new Foo();
Foo.bar = 'bar';
console.log('From bar', Foo);
});
define('Other', ['Foo'], function(Foo) {
console.log('From the other', Foo);
});
require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) {
console.log('Bringing it all together');
});
http://jsfiddle.net/radu/Zhyx9/
如果没有 require,我会做类似的事情:
App = {};
App.Foo = function() {
this.foo = 'foo';
}
App.Bar = function() {
App.Foo = new App.Foo();
App.Foo.bar = 'bar';
console.log('From bar', App.Foo);
}
App.Other = function() {
console.log('From other', App.Foo);
}
App.Bar();
App.Other();
http://jsfiddle.net/radu/eqxaA/
我知道我一定在这里遗漏了一些东西,因为这是我第一次尝试 requirejs,所以可能混入了某种误解。这个例子可能看起来很做作,但我在将项目硬塞进 using 时遇到了类似的事情主干和 RequireJS。
最佳答案
您使用 return
从模块中公开的内容可以从表示需要模块中的该模块的参数访问
define('Bar', ['Foo'], function(Foo) {
Foo = new Foo();
Foo.bar = 'bar';
//return instantiated Foo
return Foo;
});
require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) {
//Bar is the instantiated Foo, exposed from Bar
console.log(Bar);
});
关于javascript - 在 requirejs 中共享实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12361875/