javascript - 在 requirejs 中共享实例化对象

标签 javascript requirejs

我正在定义一个模块 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 从模块中公开的内容可以从表示需要模块中的该模块的参数访问

Here's your demo, modified

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/

相关文章:

javascript - 为什么javascript `for`循环会快速静音/取消静音视频

javascript - Electron:ES模块的require()

javascript - 从输入中提取图像

javascript - Webpack 动态加载代码拆分包

requirejs - 对于不同的优化选项,在 grunt 中有超过 1 个 requirejs 任务

javascript - 需要在另一个脚本中定义的模块

javascript - Gulp 任务创建 main.js 的 DEV 和 PROD 版本

javascript - 将 Java 脚本分配给克隆的 HTML 元素

javascript - 使用 jquery 选择器选择 optgroup 在第一次选择后停止工作

node.js - 防止 RequireJS 在 Nodejs 上缓存所需的脚本