gpt4 book ai didi

javascript - JavaScript 中的函数作用域

转载 作者:行者123 更新时间:2023-11-30 08:58:14 24 4
gpt4 key购买 nike

在 Pro JavaScript with Mootools 书中我找到了下面这行

The scoping rules for function expressions are a bit different from function 
declarations because they depend on variable scoping. Remember that in
JavaScript, the var keyword defines a variable to be scoped locally, and
omitting the keyword creates a global variable instead:

根据我的理解,我编写了以下代码并尝试检查它

var a = function(){ 
b = function(){ c = function(){ alert("b"); }; };
};
alert(typeof a); // Returned me 'function'
alert(typeof b); // Returned me 'undefined'
alert(typeof c); // Returned me 'undefined'

下面我也试过了

var a = function(){ 
var b = function(){ c = function(){ alert("b"); }; };
};
alert(typeof a); // Returned me 'function'
alert(typeof b); // Returned me 'undefined'
alert(typeof c); // Returned me 'undefined'​​

请你解释一下,让我更好地理解。根据我对第一段代码 b 和 c 的理解应该是全局变量。但在这种情况下不会发生这种情况。即使我试图在警报之前调用 a()... Here是 fiddle 。请帮助我更好地理解范围。

最佳答案

As per my understanding in first block of code b and c should be global variables

它们是,但直到 a 才会为它们分配值被调用(直到 bc 的情况下被调用)。

Here is the fiddle

那个代码是不同的。你有 var b ,这使得 b局部变量而不是全局变量。


var a = function(){ 
b = function(){ c = function(){ alert("b"); }; };
};
a();
b();
alert(typeof a);
alert(typeof b);
alert(typeof c);

关于javascript - JavaScript 中的函数作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11540329/

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