CoffeeScript 中的匿名函数语法
我一直在查看 CoffeeScript ,但我不明白您将如何编写这样的代码。它如何处理语法中的嵌套匿名函数?
;(function($) {
var app = $.sammy(function() {
this.get('#/', function() {
$('#main').text('');
});
this.get('#/test', function() {
$('#main').text('Hello World');
});
});
$(function() {
app.run()
});
})(jQuery);
I've been looking at CoffeeScript and I'm not understanding how you would write code like this. How does it handle nested anonymous functions in its syntax?
;(function($) {
var app = $.sammy(function() {
this.get('#/', function() {
$('#main').text('');
});
this.get('#/test', function() {
$('#main').text('Hello World');
});
});
$(function() {
app.run()
});
})(jQuery);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上并没有编译它,但这应该可以工作
didn't actually compile it, but this should work
Matt 的答案是正确的,但这里有一个替代方法:
在 CoffeeScript 1.0(在提出这个问题几周后发布)中,引入了一个
do
运算符,它运行紧随其后的函数。它主要用于捕获循环中的变量,因为(将对
x
的引用传递到匿名函数中)的行为与后者不同,后者只会重复输出
arr
中的最后一个条目,因为只有一个x
。无论如何,您应该意识到
do
作为一种运行匿名函数而无需额外括号的方式,尽管它在参数传递方面的功能目前有点有限。我提出了扩大范围的提案。目前,您的代码示例的等效项是
如果我的提案被接受,则可以
改为编写。
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(which passes a reference to
x
into the anonymous function) behaves differently thanThe latter will simply output the last entry in
arr
repeatedly, since there's only onex
.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.Currently, the equivalent of your code example would be
If my proposal is accepted, it will be possible to write
instead.
短款
Short variant