admin管理员组

文章数量:1295856

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 piled to JavaScript, it bees:

(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,

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 piled to JavaScript, it bees:

(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,

Share Improve this question asked Oct 25, 2011 at 13:39 Xi 张熹Xi 张熹 11.1k19 gold badges63 silver badges89 bronze badges 3
  • 6 Speaking as a mathematician, this is exactly why parentheses were invented in the first place. – Blazemonger Commented Oct 25, 2011 at 13:46
  • 3 Do not nest bracketless function calls, ever, in Ruby, or CoffeeScript, or any other language that allows them. The fact those even allow omitting the brackets anywhere except in the outermost of nested function calls instead of bailing with a syntax error is a horrible misfeature. – millimoose Commented Oct 25, 2011 at 13:50
  • @Xi you can use parenthesis. Please, please, please, do it. It is not because you are using CoffeeScript that you have to avoid parenthesis at all costs... – brandizzi Commented Oct 25, 2011 at 14:38
Add a ment  | 

2 Answers 2

Reset to default 9

As I explain in my book, there's no way for the piler to know what rule you want to use for implicit parentheses. Sure, in the case

times plus 1,2, minus 5,2

it's obvious to a human that you'd want it to mean

times(plus(1,2), minus(5,2))

But you might also write

times 5, plus 1, parseInt str, 10

and expect it to be understood (as it is) as

times(5, plus(1, parseInt(str, 10))

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

times plus(1,2), minus(5,2)

Not bad, right?

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:

times (plus 1, 2), (minus 5, 2)

Of course, it's only a matter of taste; the times plus(1, 2), minus(5, 2) version works just as well.

本文标签: javascriptHow does CoffeeScript decide function parameter prioritiesStack Overflow