gpt4 book ai didi

javascript - coffeescript 默认参数在未传递时不会分配给与 arg 同名的外部变量

转载 作者:行者123 更新时间:2023-12-02 06:22:18 25 4
gpt4 key购买 nike

谁能解释为什么这行不通?我只是从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com