Javascript CoffeeScript 中的匿名函数语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4166445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Anonymous functions syntax in CoffeeScript
提问by Handloomweaver
I've been looking at CoffeeScriptand I'm not understanding how you would write code like this. How does it handle nested anonymous functions in its syntax?
我一直在研究CoffeeScript,但我不明白您将如何编写这样的代码。它如何处理其语法中的嵌套匿名函数?
;(function($) {
var app = $.sammy(function() {
this.get('#/', function() {
$('#main').text('');
});
this.get('#/test', function() {
$('#main').text('Hello World');
});
});
$(function() {
app.run()
});
})(jQuery);
回答by Matt Briggs
didn't actually compile it, but this should work
实际上并没有编译它,但这应该可以工作
(($) ->
app = $.sammy ->
this.get '#/', ->
$('#main').text ''
this.get '#/test', ->
$('#main').text 'Hello World'
$(->
app.run()
)
)(jQuery);
回答by Trevor Burnham
Matt's answer is correct, but here's an alternative method:
马特的回答是正确的,但这里有一个替代方法:
In CoffeeScript 1.0 (released a few weeks after this question was posed), a do
operator was introduced that runs the function that immediately follows it. It's mostly used for capturing variables in loops, since
在 CoffeeScript 1.0(在提出这个问题几周后发布)中,do
引入了一个运算符来运行紧随其后的函数。它主要用于在循环中捕获变量,因为
for x in arr
do (x) ->
setTimeout (-> console.log x), 50
(which passes a reference to x
into the anonymous function) behaves differently than
(将引用传递给x
匿名函数)的行为与
for x in arr
setTimeout (-> console.log x), 50
The latter will simply output the last entry in arr
repeatedly, since there's only one x
.
后者将简单地arr
重复输出最后一个条目,因为只有一个x
.
Anyway, you should be aware of do
as a way of running an anonymous function without the extra parentheses, though its capabilities with respect to argument-passing are a bit limited at the moment. I've raised a proposal to broaden them.
无论如何,您应该意识到do
这是一种无需额外括号即可运行匿名函数的方式,尽管目前它在参数传递方面的能力有些有限。我提出了扩大它们的建议。
Currently, the equivalent of your code example would be
目前,相当于您的代码示例是
do ->
$ = jQuery
...
If my proposal is accepted, it will be possible to write
如果我的提议被接受,就可以写
do ($ = jQuery) ->
...
instead.
反而。
回答by lexich
Short variant
短款
do ($=jQuery)->
app = $.sammy ->
@get '#/', -> $("#main").text ''
@get '#/test', -> $('#main').text 'Hello world'
$ -> app.run()