gpt4 book ai didi

JavaScript 范围

转载 作者:行者123 更新时间:2023-12-03 11:35:17 29 4
gpt4 key购买 nike

为什么下面的代码输出4?谁能给我推荐一篇好文章来深入学习 javascript 范围。

这段代码返回4,但我不明白为什么?

(function f(){  

return f();

function f(){
alert(4);
};

var f = function (){
alert(5);
};

})();

但是此代码片段返回 5。为什么?

(function f(){
var f = function (){
alert(5);
};
return f();
function f(){
alert(4);
};
})();

最后一个返回 4。我没明白。

(function f(){
function f(){
alert(4);
};
return f();
var f = function (){
alert(5);
};
})();

为什么return f();不调用父函数f()?

最佳答案

这与范围无关,这与 entering an execution context 时发生的情况有关。 .

简而言之,当进入执行上下文(例如函数)时,会创建变量并为其分配未定义的值。变量声明如下:

var f = 5;

创建变量f,但值5直到运行时并执行该语句才被分配。

然后处理函数声明,这会有效地创建一个具有该名称的局部变量,并将函数体指定为其值。

然后开始执行。

发生了更多事情,但这就是这里重要的部分。

如下:

// The optional name creates a local variable f at parse time that
// references this function. In some buggy versions of IE, it also creates
// a global f variable that references the function.
(function f(){

// This is the only statement in f's execution context that is executed.
return f();

// This defines a function f at parse time, after the variable declaration below,
// and overriding the initial f created
// above, immediately before any code is executed. It is this
// function that is executed by the return statement
function f(){
alert(4);
};

// The variable declaration is processed before the above function declaration
// and before any code is run. But since f
// already exists because of the optional name, it has no effect.
// Since this is below the return, the assignment is never executed.
var f = function (){
alert(5);
};
})();

适用于其他示例。

(function f(){

// Everything happens as above, but because this assignment is before the
// return, it happens after variable function declarations, so when
// executed it replaces the function created by the function declaration below.
var f = function (){
alert(5);
};
return f();

// This function is created before any code is executed, but is over ridden
// by the assignment above at runtime
function f(){
alert(4);
};
})();

最后一个:

(function f(){
function f(){
alert(4);
};
return f();

// As with the first, this assignment never happens so
// when f is called above, it calls the function created by
// the function declaration.
var f = function (){
alert(5);
};
})();

关于JavaScript 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26542361/

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