gpt4 book ai didi

Javascript 命名函数定义在不应该执行的时候执行

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:50 25 4
gpt4 key购买 nike

我不知道这里发生了什么。代码是:

  if( true ) { 

console.log('In first function definition');

function test(){
console.log('Hello world');
}

} else {

console.log('In the second function definition');

function test(){
console.log('Goodbye world');
}

}

test();

我希望这会登录到控制台:

'In the first function definition'
'Hello world'

而是记录:

'In the first function definition'
'Goodbye world'

当代码没有进入该分支时,如何创建第二个命名函数?

最佳答案

请记住,JavaScript 中的所有内容都是函数范围的;没有 block 作用域。

为此,您在相同 作用域(无论 if-else 所在的作用域)中定义了两个函数声明,它们具有相同的名称,位于不同的 block 中。这会在浏览器之间产生不一致的结果。

你需要给这些函数不同的名字,或者使用函数表达式,像这样:

var f;
if(true) {
console.log('In first function definition');

f = function(){
console.log('Hello world');
};

} else {
console.log('In the second function definition');

f = function(){
console.log('Goodbye world');
};
}
f();

关于你的优秀问题

But how is the function defined, if we don't enter that branch of the code? If that block is not executed, why is scope a consideration?

简单的答案是函数声明被“提升”,并且在范围内任何地方立即可用,甚至在声明本身之前。

即:

function foo(){
f(); //perfectly valid

function f(){
}
}

更长的答案是,在进入范围之前,所有变量声明和函数声明都被剥离,并放在“激活对象”上。然后将激活对象放在“作用域链”的头部。当您执行该函数时,对这些变量和函数的任何引用都会从那里简单地解析。

关于Javascript 命名函数定义在不应该执行的时候执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930802/

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