2015-10-18 38 views
1

我试图将经典JavaScript“类”转换为AMD模块。但是,我还需要继续将类导出到全局名称空间,因为一些遗留代码需要它。我试过this,但是,全局对象没有创建。我究竟做错了什么?当不在RequireJS环境中时公开AMD模块

define('VisitorManager', function() { 

    var VisitorManager = function() { 

     "use strict"; 

     // ... 
    }; 


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


    //expose globally 
    this.VisitorManager = VisitorManager; 

    //return AMD module 
    return VisitorManager; 

}); 

回答

1

要全局公开您的模块,您需要将其注册到全局对象中。

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

window.VisitorManager = VisitorManager; 

在Node.js的环境全局对象被称为GLOBAL

GLOBAL.VisitorManager = VisitorManager; 

使用类两种旧有环境和与RequireJS,你可以使用这个技巧:

(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())(); 
    } 

})(); 
+0

我改变了我的公司de包含'window.VisitorManager = VisitorManager;'但VisitorManager类仍然没有全局公开。看起来模块中的代码甚至没有执行。 –

+1

@StevenMusumeche你在为什么开发环境?它是浏览器吗?您的.js文件是否包含此代码作为您正在加载的页面中的

相关问题