Sha*_*ean 32 javascript coffeescript
当我创建一个新的coffeescript文件时,我无法从另一个文件中访问已编译代码中的代码,因为它包含在某个函数范围内.例如:
CoffeeScript的:
class ChatService
  constructor: (@io) ->
生成的Javascript:
(function() {
  var ChatService;    
  ChatService = (function() {    
    function ChatService(io) {
      this.io = io;
    }    
    return ChatService;    
  })();    
}).call(this);
当试图调用ChatService另一个文件时,它没有定义.如何使用coffeescript处理多个文件?
Aar*_*our 56
根据这是客户端代码还是服务器端代码,有两种略有不同的方法.
客户端:在这里,我们将跨文件可用的内容附加到全局名称空间(window),如下所示:
class window.ChatService
  constructor: (@io) ->
然后,在另一个文件中同时ChatService与window.ChatService将允许访问的类.
服务器端:这里我们必须使用exports和require.在ChatService.coffee文件中,您将拥有以下内容:
class exports.ChatService
  constructor: (@io) ->
然后,从另一个文件中获取它,您可以使用:
ChatService = require('ChatService.coffee').ChatService
注意:如果您从ChatService.coffee获得了多个类,那么这是CoffeeScript的dict解包真正发光的地方,例如:
{ChatService, OtherService} = require('ChatService.coffee')
两者:基本上,我们根据我们所处的环境选择是运行服务器端代码还是客户端代码.这是一种常见的方法:
class ChatService
  constructor: (@io) ->
if typeof module != "undefined" && module.exports
  #On a server
  exports.ChatService = ChatService
else
  #On a client
  window.ChatService = ChatService
为拿到它,为实现它:
if typeof module != "undefined" && module.exports
  #On a server
  ChatService = require("ChatService.coffee").ChatService
else
  #On a client
  ChatService = window.ChatService
可以跳过第二个块的else子句,因为ChatService已经引用了附加的引用window.
如果你要在这个文件中定义很多类,可能更容易定义它们,如:
self = {}
class self.ChatService
然后将它们附加module.exports = self在服务器和_.extend(window, self)客户端上(根据需要替换_.extend为其他extend功能).
mu *_*ort 24
通常的方法是在以下位置定义全局命名空间window:
window.App = { }
在其他任何事情发生之前,这将在应用程序的初始化代码中的某处.然后,为你的班级:
class App.ChatService
  constructor: (@io) ->
这允许您通过App任何您想要的地方引用您的类,并且您不必担心污染全局命名空间:
chatter = new App.ChatService
如果你想让你的ChatService真正全球化,那么你可以使用,class window.ChatService但除了最简单的应用程序之外,我建议不要这样做.
AFAIK,node.js有类似的东西,window但我对node.js不太熟悉,告诉你它是什么.