使用 Coffeescript 公开 javascript api
我最近开始使用 Coffeescript,并且很好奇将我使用 Coffeescript 创建的对象公开给其他 javascript 页面的“正确”方法是什么。由于咖啡脚本包装功能,调用 window.coffeeObject = externalObject
的行为是否可接受。
示例
example.coffee
externalObject =
method1: -> 'Return value'
method2: -> 'Return method2'
window.myApi = externalObject
编译
(function() {
var externalObject;
externalObject = {
method1: function() {
return 'Return value';
},
method2: function() {
return 'Return method2';
}
};
window.myApi = externalObject;
}).call(this);
example.js -- 从 example.coffee other.js
alert(myApi.method1()) // Should return "Return value"
I recently started using coffeescript and was curious what is the "right" way to expose an object that I create with Coffeescript to other javascript pages. Because of coffeescripts wrapping functionality, is it acceptable behavior to call window.coffeeObject = externalObject
.
Example
example.coffee
externalObject =
method1: -> 'Return value'
method2: -> 'Return method2'
window.myApi = externalObject
example.js -- compiled from example.coffee
(function() {
var externalObject;
externalObject = {
method1: function() {
return 'Return value';
},
method2: function() {
return 'Return method2';
}
};
window.myApi = externalObject;
}).call(this);
other.js
alert(myApi.method1()) // Should return "Return value"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是正确的。或者,您可以使用define
@myApi = { foo: -> }
因为this
是文件根上下文中的window
。Yep that's correct. Alternatively you can use define
@myApi = { foo: -> }
becausethis
iswindow
in the root context of the file.您可以进一步简化语法,例如,如果您有 2 个内部函数
example.coffee
example.js
@
将是window
在文件的主要范围内。然后通过
window.myApi.myFunction()
从其他地方调用如果您想将外部函数名称映射到相同的内部名称,如果您不指定
key : value
对,默认情况下它只会使用字符串值作为键。example.coffee
example.js
You can simplify the syntax further, for example if you had 2 internal functions
example.coffee
example.js
The
@
will bewindow
within the main scope of the file.Then call from elsewhere by
window.myApi.myFunction()
If you wanted to map the external function names to the same internal names, if you don't specify
key : value
pairs, it will just use the string value as the key by default.example.coffee
example.js