Javascript 起重/范围
我现在正在学习Javascript,有一个关于提升/范围界定的问题——也许我遗漏了什么 如果我定义了一个全局变量,我不能在函数中引用该变量的值,因为它超出了范围Javascript 起重/范围,javascript,scope,scoping,hoisting,Javascript,Scope,Scoping,Hoisting,我现在正在学习Javascript,有一个关于提升/范围界定的问题——也许我遗漏了什么 如果我定义了一个全局变量,我不能在函数中引用该变量的值,因为它超出了范围 var x = "hello"; function temp(){ console.log(x); } 结果是 var x = "hello"; function temp(){ var x; console.log(x); } 这两个输出都未定义。全局变量的要点是什么,或者如何在函数中使用它们正如我所说,
var x = "hello";
function temp(){
console.log(x);
}
结果是
var x = "hello";
function temp(){
var x;
console.log(x);
}
这两个输出都未定义。全局变量的要点是什么,或者如何在函数中使用它们正如我所说,我在这里错过了什么!:)
还有起重作业的功能?但不是匿名函数?对吗
感谢您的帮助
谢谢 提升仅适用于局部变量(在当前范围内用
var
声明的变量)。由于temp()
中没有var
,因此没有提升
此处将吊装x
:
var x = "hello";
function temp(){
console.log(x); // undefined
var x = 55
}
temp()
因为这被解释为:
var x = "hello";
function temp(){
var x /* = undefined */
console.log(x);
x = 55
}
temp()
您可以访问范围或更高级别中定义的任何变量。如果在您的范围内重新声明了相同的变量名,那么这将成为一个新的变量定义,覆盖另一个变量定义 因此,通过这个例子:
var x = "hello";
function temp(){
console.log(x); // outputs "hello" when temp() is called
}
var x = "hello";
function temp(){
var x;
console.log(x); // outputs "undefined" when temp() is called
// because local var x has not been assigned a value
}
var x = 10;
function temp() {
x = 3;
y = 4;
var x;
console.log(x);
}
x
的定义范围高于函数,因此可以在函数内部使用
在本例中:
var x = "hello";
function temp(){
console.log(x); // outputs "hello" when temp() is called
}
var x = "hello";
function temp(){
var x;
console.log(x); // outputs "undefined" when temp() is called
// because local var x has not been assigned a value
}
var x = 10;
function temp() {
x = 3;
y = 4;
var x;
console.log(x);
}
您已经定义了一个新变量x
,它是函数中的一个局部变量,它的值将未定义
,直到您为它赋值为止
术语“提升”是指定义在范围内任何位置(例如函数内)的变量的行为,就好像它是在函数的最开始定义的一样,而不管声明实际出现在何处 因此,由于吊装,本例:
var x = "hello";
function temp(){
console.log(x); // outputs "hello" when temp() is called
}
var x = "hello";
function temp(){
var x;
console.log(x); // outputs "undefined" when temp() is called
// because local var x has not been assigned a value
}
var x = 10;
function temp() {
x = 3;
y = 4;
var x;
console.log(x);
}
行为类似于此,函数中对x
的所有引用都是对x
的本地版本的引用:
var x = 10;
function temp() {
var x;
x = 3;
y = 4;
console.log(x);
}
“也适用于函数?但不适用于匿名函数?对吗?”不。但函数声明和函数表达式之间存在差异。此外,第一个示例将输出“hello”,它与第二个示例不同。阅读:并链接到一个非常好的示例: