谁能解释为什么这行不通?我只是从 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 )
感谢一百万!
最佳答案
看看函数是如何编译的,问题就很明显了:
foo = function(x) {
if (x == null) x = x;
return console.log(x ? "works" : "nope");
};
如您所见,如果 x
参数为 null,则将 x
分配给它。所以它仍然是空的。
因此,将 x
变量重命名为 y
可以解决问题:
y = true
foo = (x = y) ->
console.log if x then "works" else "nope"
foo() # "nope"
关于javascript - coffeescript 默认参数在未传递时不会分配给与 arg 同名的外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126912/