2015-10-18 37 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文件是否包含此代碼作爲您正在加載的頁面中的

相關問題