Coffee Script had fixed quite a lot of pitfalls in Javascript. But on another hand it also introduced some other pitfalls, the most common one is the space.
Space in function declaration
Read the following code:
|
|
This is a quite simple script, but it failed to run. And if you might also feel confused about the error message: “message is not defined”
What happened to the code? We indeed had declared the message as argument of function show. To reveal the answer, we should analyze the compiled javascript.
Here is the compiled code:
|
|
Look the fun declaration, you will see it is not a function declaration as we want but a function call.
The reason is that we omitted the parentheses around the argument and we add a new space between message
and ->
. So the coffee-script compiler interpret message as a function call with a function as parameter.
Soltuion
To fix this problem, we can remove the space between message
and ->
to enforce coffee-script compiler interpret them as a whole.
|
|
Best Practise
To avoid this pitfall, my suggestion is never omit the parentheses around the arguments, even there is only one argument.
And also including the function call, even coffee-script allow to omit the parentheses. Since you won’t able to chain the method call if you omit the parentheses.
So never omit parentheses, unless you are very certain that there is no any ambiguity and you won’t use method chain.
The space in array index
Since coffee script doesn’t support the negative index. So we should use following code as negative index:
|
|
This piece of code is also failed to run, and the error message is “property of object is not a function”.
Quite wield right?
Let’s see what is behind the scene, here is the compiled code:
|
|
Same problem, heros.length -1
is interpreted as heros.length(-1)
instead of heros.length -1
.
To fix this problem, we should write the code in following way:
|
|
Or
|
|
Both solution is try to enforce the compiler divid the component in correct way.
And unfortunately, there is no way to avoid this problem, the only thing you can do is always be aware the spaces in expression.