CoffeeScript 如何决定函数参数优先级?
假设我们有 3 个函数:times、plus 和 minus。他们按照他们的名字所暗示的去做。然后,我们在 JavaScript 中创建以下行:
times(plus(1,2) ,minus(5,2));
当用 CoffeeScript 编写时,它是:
times plus 1,2 , minus 5,2
编译为 JavaScript 后,它变成:
(function() {
times(plus(1, 2, minus(5, 2)));
}).call(this);
这不是我们想要的。有没有 CoffeeScript 方法来解决这个问题,或者我们必须使用括号?谢谢,
Suppose we have 3 functions: times, plus and minus. They do what their name suggest. We then create the following line in JavaScript:
times(plus(1,2) ,minus(5,2));
When written in CoffeeScript, it's:
times plus 1,2 , minus 5,2
And after compiled to JavaScript, it becomes:
(function() {
times(plus(1, 2, minus(5, 2)));
}).call(this);
Which is not what we want. Is there a CoffeeScript way to solve this or we have to use brackets? Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如我在我的书中解释的那样,编译器无法知道您要对隐式括号使用什么规则。当然,在这种情况下,
对于人类来说,你想要它的意思是显而易见的,
但你也可能会编写
并期望它被理解为(按原样)
CoffeeScript 隐式括号的规则非常简单:它们到最后的表达式。因此,例如,您始终可以将 Math.floor 粘贴在数学表达式前面。
作为一种风格问题,我通常只在一行中的第一个函数调用时省略括号,从而避免任何潜在的混淆。这意味着我会把你的例子写成
“不错”,对吧?
As I explain in my book, there's no way for the compiler to know what rule you want to use for implicit parentheses. Sure, in the case
it's obvious to a human that you'd want it to mean
But you might also write
and expect it to be understood (as it is) as
The rule for CoffeeScript's implicit parentheses is very simple: They go to the end of the expression. So, for instance, you can always stick
Math.floor
in front of a mathematical expression.As a stylistic matter, I generally only omit parens for the first function call on a line, thus avoiding any potential confusion. That means I'd write your example as
Not bad, right?
作为“常规”函数调用括号的替代方案,您可以对函数call使用无括号样式,并仅针对优先级使用括号,例如:
当然,这只是一个品味问题;
times plus(1, 2), minus(5, 2)
版本也同样有效。As an alternative to the "regular" function-call parens, you can use the paren-less style for the function call and parens only for precedence, such as:
Of course, it's only a matter of taste; the
times plus(1, 2), minus(5, 2)
version works just as well.