在Coffeescript.org上:
bawbag = (x, y) ->
z = (x * y)
bawbag(5, 10)
Run Code Online (Sandbox Code Playgroud)
会编译为:
var bawbag;
bawbag = function(x, y) {
var z;
return (z = (x * y));
};
bawbag(5, 10);
Run Code Online (Sandbox Code Playgroud)
通过node.js下的coffee-script编译包装如下:
(function() {
var bawbag;
bawbag = function(x, y) {
var z;
return (z = (x * y));
};
bawbag(5, 10);
}).call(this);
Run Code Online (Sandbox Code Playgroud)
文件说:
如果要为其他要使用的脚本创建顶级变量,请将它们作为属性附加到窗口或CommonJS中的exports对象上.存在运算符(如下所述)为您提供了一种可靠的方法来确定添加它们的位置,如果您的目标是CommonJS和浏览器:root = exports?这个
如何在CoffeeScript中定义全局变量."将它们作为窗口上的属性附加"是什么意思?
如何省略将变量隐藏在全局范围内的自动闭包?
(function() {
// my compiled code
}).call(this);
Run Code Online (Sandbox Code Playgroud)
只是玩弄CoffeeScript + SproutCore,当然,我更愿意保留原样:在这种情况下,没有必要保护任何东西不被覆盖.
我知道我可以使用@或this.在声明,但这不是太优雅.
我最近开始使用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)