如果两者都具有相同的变量名称 n 声明,则执行哪个函数?

Which function is executed if both has same variable names n declared?

提问人:sujithrakumaran 提问时间:11/1/2023 最后编辑:VLAZsujithrakumaran 更新时间:11/1/2023 访问量:89

问:

let foo = function(){
    console.log(1);
}
setTimeout (foo,1000);

foo = function(){
    console.log(2);
}  

我得到的输出是 1。但我需要知道为什么,因为 let 可以重新初始化,所以它在这里是正确的,为什么我没有得到 o/p 为 2?

JavaScript 函数 变量

评论

2赞 VLAZ 11/1/2023
按预期工作:JavaScript 是按引用传递还是按值传递语言?读取值,JS 不会跟踪对变量的更改。这与 - 该值已被读取和使用的情况相同。不会转换为已执行的 for 代码。let x = 1; console.log(x); x = 2;12
0赞 deceze 11/1/2023
您将函数传递给 ,而不是变量名称或变量。setTimeout
0赞 sujithrakumaran 11/1/2023
但是这里的函数是使用变量 foo 调用的,对吧?所以 foo 是否是一个变量
0赞 Quentin 11/1/2023
@sujithrakumaran — 不,它不是这样调用的。是的,foo 是一个变量。该函数是通过从变量中读取对它的引用并将该引用传递给(然后是接管的内部结构,并在一秒钟后调用)来调用该函数。foosetTimeoutsetTimeout

答:

0赞 Dimuthu 11/1/2023 #1

运行此行时未声明第二个变量,您可以通过注释setTimeout (foo,1000); let foo = function(){ console.log(1); }

评论

0赞 sujithrakumaran 11/1/2023
aint javascript 跟随吊装?那么为什么不能吊起来呢?let foo = function(){ console.log(2); }
0赞 Quentin 11/1/2023
@sujithrakumaran — 函数声明的值被提升,这是一个函数表达式。
0赞 VLAZ 11/1/2023
@sujithrakumaran吊装与您显示的代码无关。参见 var functionName = function() {} vs function functionName() {} |为什么函数声明会被提升,而函数表达式不会?|函数表达式提升?
0赞 Community 11/3/2023
正如目前所写的那样,你的答案尚不清楚。请编辑以添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以在帮助中心找到有关如何写出好答案的更多信息。