理解JavaScript函数范围 [英] Understanding JavaScript function scoping
问题描述
以下代码是JavaScript代码。我试图了解JavaScript中的函数范围,并关注此处的文章。我正在复制下面的代码 -
The code below is JavaScript code. I am trying to understand function scope in JavaScript and following the article over here. I am reproducing the code below -
var cow = "purple"; // just a random cow
var f = function (x) {
var r = 0;
cow = "glue";
if (x > 3) {
var cow = 1; // a local variable
r = 7;
}
return r;
};
var z = f(2);
alert(cow); // returns purple
我不太明白为什么字符串purple会被警告。行 cow =glue;
应该将cow变量的值设置为glue。如果我删除了if块,然后在最后一个语句中警告cow,我看到字符串glue被警告。
I don't quite understand why the string "purple" is alerted. The line cow = "glue";
should set the value of the cow variable to "glue". If I remove the if block, and then alert cow in the last statement, I see that the string "glue" is alerted.
当调用f(2)时,如果没有输入if代码块并且其中没有任何内容被执行,那么为什么我会看到不同的结果呢?即为什么在最后一个语句中警告牛现在返回字符串紫色?
When f(2) is called, the if code block is not entered and nothing in it gets executed, so why do I see different results ? i.e why does alerting cow in the last statement return the string "purple" now ?
推荐答案
函数内的变量声明总是被提升到顶端。所以你的代码实际上是:
Variable declarations inside functions are always hoisted to the top. So your code is actually:
var f = function (x) {
var cow, r;
r = 0;
cow = "glue";
if (x > 3) {
cow = 1; // a local variable
r = 7;
}
return r;
};
在函数内部,您总是分配给 local cow
,绝不是全球。
Inside the function you're always assigning to the local cow
, never the global.
这篇关于理解JavaScript函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!