提问人:sujithrakumaran 提问时间:11/1/2023 最后编辑:VLAZsujithrakumaran 更新时间:11/1/2023 访问量:89
如果两者都具有相同的变量名称 n 声明,则执行哪个函数?
Which function is executed if both has same variable names n declared?
问:
let foo = function(){
console.log(1);
}
setTimeout (foo,1000);
foo = function(){
console.log(2);
}
我得到的输出是 1。但我需要知道为什么,因为 let 可以重新初始化,所以它在这里是正确的,为什么我没有得到 o/p 为 2?
答:
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() {} |为什么函数声明会被提升,而函数表达式不会?|函数表达式提升?
评论
let x = 1; console.log(x); x = 2;
1
2
setTimeout
foo
setTimeout
setTimeout