用coffeescript公开一个javascript api

bre*_*ent 14 javascript coffeescript

我最近开始使用coffeescript,很好奇将我用Coffeescript创建的对象暴露给其他javascript页面的"正确"方法是什么.由于coffeescripts包装功能,是否可以接受调用行为window.coffeeObject = externalObject.

example.coffee

externalObject = 
   method1: -> 'Return value'
   method2: -> 'Return method2'

window.myApi = externalObject
Run Code Online (Sandbox Code Playgroud)

example.js - 从example.coffee编译

(function() {
  var externalObject;
  externalObject = {
    method1: function() {
      return 'Return value';
    },
    method2: function() {
      return 'Return method2';
    }
  };
  window.myApi = externalObject;
}).call(this);
Run Code Online (Sandbox Code Playgroud)

other.js

alert(myApi.method1()) // Should return "Return value"
Run Code Online (Sandbox Code Playgroud)

Ale*_*yne 5

是的,这是正确的.或者,您可以使用define,@myApi = { foo: -> }因为thiswindow位于文件的根上下文中.