为什么这个JavaScript代码的结果是;未定义的“;?
我试图弄明白为什么浏览器控制台窗口中的Javascript代码的结果是未定义的?不应该是“外面”吗为什么这个JavaScript代码的结果是;未定义的“;?,javascript,function,logging,scope,output,Javascript,Function,Logging,Scope,Output,我试图弄明白为什么浏览器控制台窗口中的Javascript代码的结果是未定义的?不应该是“外面”吗 谢谢您正在覆盖变量文本。要得到答案,您需要从第四行获取var 原因是函数内部有一个来自父作用域或全局作用域的名为text的变量,您正在更改它,然后在离开函数时将其处理。这是“变量提升”的结果。(见附件。) var text = 'outside'; function logIt(){ console.log(text); // logs 'outside' now text = '
谢谢您正在覆盖变量文本。要得到答案,您需要从第四行获取var 原因是函数内部有一个来自父作用域或全局作用域的名为text的变量,您正在更改它,然后在离开函数时将其处理。这是“变量提升”的结果。(见附件。)
var text = 'outside';
function logIt(){
console.log(text); // logs 'outside' now
text = 'inside';
}
logIt();
要使代码按预期运行,您需要在函数范围内分配变量或将其作为参数传递给函数:
var logIt = function (){
var text = 'outside';
console.log(text);
text = 'inside';
};
logIt();
或
在JavaScript中,变量被“提升”到函数的顶部。也就是说,与其他一些语言(如C)不同,函数中声明的变量在整个函数的作用域内。因此,编译器看到的函数如下所示:
function logIt(){
var text;
console.log(text);
text = 'inside';
} // <-- no semicolon after a function declaration
声明变量
text
一次
全局+局部:一个非常复杂的情况
var x = 5;
(function () {
console.log(x);
var x = 10;
console.log(x);
})();
这将打印出未定义的和10,而不是5和10,因为JavaScript总是将变量声明(不是初始化)移动到作用域的顶部,使代码等效于:
var x = 5;
(function () {
var x;
console.log(x);
x = 10;
console.log(x);
})();
从这个答案中您的console.log(文本)位置错误:) 但说真的,这是Javascript变量提升 这: 相当于:
var text // hoisted to top of scope; text is undefined
text = 'outside' // text is now assigned in place
logIt = function () {
var text; // hoisted to top of scope; text is undefined
console.log(text); // spits out undefined
text = 'inside'; // text is now assigned in place.
}
logIt();
为了避免此类问题,养成在作用域块顶部声明所有var的习惯
var text = 'outside'
logIt = function() {
var text = 'inside'
console.log(text)
}
logIt()
如果您的意图是吐出“outside”,那么您应该在logIt函数中使用不同的标识符名称。不,不会。由于变量提升,而不是函数提升,代码的行为与之类似。您给出的参考是404
var text = 'outside';
function logIt(){
console.log(text); // logs 'outside' now
text = 'inside';
}
logIt();
var text = 'outside'
logIt = function () {
console.log(text);
var text = 'inside';
}
logIt();
var text // hoisted to top of scope; text is undefined
text = 'outside' // text is now assigned in place
logIt = function () {
var text; // hoisted to top of scope; text is undefined
console.log(text); // spits out undefined
text = 'inside'; // text is now assigned in place.
}
logIt();
var text = 'outside'
logIt = function() {
var text = 'inside'
console.log(text)
}
logIt()