不在 RequireJS 环境中时全局公开 AMD 模块

Expose AMD module globally when not in a RequireJS environment

我正在尝试将 classic JavaScript "class" 转换为 AMD 模块。但是,我还需要继续将 class 导出到全局命名空间中,因为一些遗留代码需要它。我试过 this,但是,没有创建全局对象。我做错了什么?

define('VisitorManager', function () {

    var VisitorManager = function () {

        "use strict";

        // ...
    };


    VisitorManager.prototype.hasExistingChat = function () {
        // ...
    };


    //expose globally
    this.VisitorManager = VisitorManager;

    //return AMD module
    return VisitorManager;

});

要在全局公开您的模块,您需要在全局对象中注册它。

在浏览器中全局对象是window:

window.VisitorManager = VisitorManager;

在 Node.js 环境中,全局对象被称为 GLOBAL:

GLOBAL.VisitorManager = VisitorManager;

要在遗留环境和 RequireJS 中使用 class,您可以使用这个技巧:

(function() {

    var module = function() {

        var VisitorManager = function() {
            "use strict";

            // ...
        };

        // Return the class as an AMD module.
        return VisitorManager;
    };

    if (typeof define === "function" && typeof require === "function") {
        // If we are in a RequireJS environment, register the module.
        define('VisitorManager', module);
    } else {
        // Otherwise, register it globally.
        // This registers the class itself:
        window.VisitorManager = module();

        // If you want to great a global *instance* of the class, use this:
        // window.VisitorManager = new (module())();
    }

})();