CoffeeScript 默认参数在未传递时不会分配给与 arg 同名的外部变量
谁能解释为什么这行不通?我只是在 CoffeeScript 页面的“立即尝试 Coffeescript”中运行它,我的 Chrome 控制台会记录“不”,如下所示
x = true
foo = (x = x) ->
console.log if x then "works" else "nope"
foo() # "nope"
如果我将 x = true 更改为 y = true 并将 ( x = x) 更改为( x = y ) 在参数定义中
谢谢一百万!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看函数是如何编译的,问题就很明显了:
如您所见,如果
x
参数为 null,则将x
分配给它。所以它仍然为空。因此,将
x
变量重命名为y
可以解决该问题:Seeing how the function is compiled makes the problem obvious:
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 toy
fixes the problem:阿诺的回答是正确的。这种方法也有效:
do
语法使您在函数中捕获变量时不必重命名变量。编辑:实际上,这段代码在当前版本的 CoffeeScript 中给出了
"nope"
,尽管do (x) ->
会给你 <代码>“有效”。请参阅下面我的评论。arnaud's answer is correct. This approach also works:
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, thoughdo (x) ->
will give you"works"
. See my comment below.