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”
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
->. So the coffee-script compiler interpret message as a function call with a function as parameter.
To fix this problem, we can remove the space between
-> to enforce coffee-script compiler interpret them as a whole.
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.
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:
heros.length -1 is interpreted as
heros.length(-1) instead of
To fix this problem, we should write the code in following way:
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.