javascript - coffeescript default argument, when not passed, is not assigned to an outside variable with same name as arg - Stac

Can anyone explain why this won't work? I am just running this off of the CoffeeScript page's

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 badges
Add a ment  | 

2 Answers 2

Reset to default 10

Seeing 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信