coffeescript default argument, when not passed, is not assigned to an outside variable with same name as arg
Can anyone explain why this won't wor开发者_StackOverflowk? I am just running this off of the CoffeeScript page's "Try Coffeescript now" thing and my Chrome console logs the "nope" as you'll see below
x = true
foo = (x = x) ->
console.log if x then "works" else "nope"
foo() # "nope"
If I had changed the x = true to y = true and ( x = x) to ( x = y ) in the argument definition
Thanks a million!
Seeing how the function is compiled makes the problem obvious:
foo = function(x) {
if (x == null) x = x;
return console.log(x ? "works" : "nope");
};
As you can see, if the x
argument is null, x
is assigned to it. So it's still null.
So, renaming the x
variable to y
fixes the problem:
y = true
foo = (x = y) ->
console.log if x then "works" else "nope"
foo() # "nope"
arnaud's answer is correct. This approach also works:
x = true
do foo = (x) ->
console.log if x then "works" else "nope"
The do
syntax spares you from having to rename variables when capturing them in a function.
Edit: Actually, this code gives "nope"
in the current version of CoffeeScript, though do (x) ->
will give you "works"
. See my comment below.
精彩评论