问题
When I invoke a function with a space before the parens, it gives an error saying unepected ,
sum = (a, b) ->
a+b
console.log (sum (1, 2))
error: unexpected ,
console.log (sum (1, 2))
it points to the comma between 1 and 2
Why the odd behavior?
回答1:
In CoffeeScript you can write function calls in two ways:
foo(bar) # with parens
foo bar # without parens
Since you have a space between sum
and (1, 2)
, then you are making a unparenthesized functional call of sum
passing (1, 2)
as the first parameter, equivalent to this:
bar = (1, 2)
sum bar
The problem is that (1, 2)
is not a valid CoffeeScript expression. To pass two parameters, you have to use either of:
sum(1, 2)
sum 1, 2
回答2:
Parentheses serve various purposes in CoffeeScript; the purposes that are relevant here are:
- Grouping within expressions.
- Function calls.
The parentheses for functions calls are often optional so you can say this:
console.log 6, 11
and everything's fine. The problem occurs when there is some ambiguity between grouping parentheses and function calling parentheses. Consider this:
f = (n) -> 2*n
f (1 + 2) + 3
What is the result? If the parentheses are for grouping then we have:
x = (1 + 2) + 3 # 6
f x # 12
but if the parentheses indicate a function call then we have:
x = 1 + 2 # 3
y = f x # 6
y + 3 # 9
So there is some ambiguity about what the parentheses mean and the result of the expression depends on how that ambiguity is resolved. If there is a space between the function name and the opening parentheses:
f (1 + 2) + 3
then CoffeeScript uses the parentheses for grouping and, filling in the optional parentheses, the function call is seen like this:
x = (1 + 2) + 3
f(x)
However, if there isn't any space then it is seen as:
x = (1 + 2)
f(x) + 3
So if there is a space before the opening parentheses then CoffeeScript assumes that it should fill in the implied parentheses for the function call; if there isn't a space then the parentheses are seen as explicit rather than implied.
Now we can look at your specific case:
console.log (sum (1, 2))
The spaces after log
and sum
indicate that the parentheses are used for grouping and (1, 2)
isn't a valid CoffeeScript expression.
Rule of thumb: if you want (or need) to use parentheses to indicate a function call then don't put any space between the function name and the opening parenthesis.
来源:https://stackoverflow.com/questions/16985675/coffeescript-invoking-function-with-space-before-parens