Can anyone explain why this won't work? 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!
Can anyone explain why this won't work? 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!
Share Improve this question edited Aug 19, 2011 at 20:46 Arnaud Le Blanc 99.9k24 gold badges211 silver badges196 bronze badges asked Aug 19, 2011 at 20:13 Nik SoNik So 16.8k21 gold badges75 silver badges108 bronze badges2 Answers
Reset to default 10Seeing how the function is piled 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 ment below.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742302202a4418235.html
评论列表(0条)