RequireJS 中的单例

Singleton in RequireJS

我想用 RequireJS 做一个简单的单例。

像这样:

// js/modules/singleton.js
define([], function () {
    var Singleton = function() {
        this.value = 10;
    }
    return new Singleton();
 });

在我的主条目中有以下代码:

    // main.js
    require.config({
          paths: {
            singleton: 'js/modules/singleton'
          },
          shim: {

          }
    });

    var o1 = require(["singleton"]);  
    var o2 = require(["singleton"]);

console.log(o1 === o2);     // true
console.log(o1.value);      // undefined (?!)
console.log(o2.value);      // undefined (?!)

o1.value = 20;
console.log(o1.value);      // 20
console.log(o2.value);      // 20

o2.value = 30;
console.log(o1.value);      // 30
console.log(o2.value);      // 30

变量 o1 和 o2 正确指向同一个单例实例 (o1 === o2),但为什么 o1.valueo2.value未定义??

我希望属性 "value" 像这样 =10,因为它是这样初始化的。

你的问题几乎是竞争条件。

这样的简单(同步!)调用
var o1 = require(["singleton"]);

returns 模块只是,如果它以前使用异步版本加载 require()

因此,要解决您的问题,只需将您的代码包装在异步 require() 调用中,如下所示:

require( ['singleton'], function( singleton ){

    o1 = singleton;
    o2 = singleton;

    console.log(o1 === o2);     // true
    console.log(o1.value);      // 10
    console.log(o2.value);      // 10

    o1.value = 20;
    console.log(o1.value);      // 20
    console.log(o2.value);      // 20

    o2.value = 30;
    console.log(o1.value);      // 30
    console.log(o2.value);      // 30
});

Example Fiddle

Citing the RequireJS documentation (highlighting added):

Console debugging: If you need to work with a module you already loaded via a require(["module/name"], function(){}) call in the JavaScript console, then you can use the require() form that just uses the string name of the module to fetch it:

require("module/name").callSomeFunction()

Note this only works if "module/name" was previously loaded via the async version of require: require(["module/name"]). If using a relative path, like './module/name', those only work inside define