我正在尝试弄清楚为什么在浏览器控制台窗口中运行此JavaScript代码的结果是未定义的?难道不应该是“外部”吗?
var text = 'outside';
function logIt(){
console.log(text);
var text = 'inside';
};
logIt();
谢谢
我正在尝试弄清楚为什么在浏览器控制台窗口中运行此JavaScript代码的结果是未定义的?难道不应该是“外部”吗?
var text = 'outside';
function logIt(){
console.log(text);
var text = 'inside';
};
logIt();
谢谢
var logIt = function (){
var text = 'outside';
console.log(text);
text = 'inside';
};
logIt();
或者
var text = 'outside';
var logIt = function (txtArg){
console.log(txtArg);
var text = 'inside';
};
logIt(text);
function logIt(){
var text;
console.log(text);
text = 'inside';
} // <-- no semicolon after a function declaration
当你在logIt
内部声明text
作为局部变量时,它会遮盖外层作用域中的变量。而当一个变量被声明时,它被初始化为undefined。这就是为什么会输出undefined的原因。
如果你想保留外部作用域中的text
,只需在函数内部省略var
声明即可。
var text = 'outside';
function logIt(){
console.log(text); // logs 'outside' now
text = 'inside';
}
logIt();
您的console.log(text)放置在错误的位置 :)
但是,这是Javascript变量提升。http://goo.gl/0L8h5D
这个:
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()
声明变量text
一次。演示
var text = 'outside';
function logIt(){
console.log(text);
text = 'inside';
};
logIt();
全局+本地:一个额外复杂的情况
var x = 5;
(function () {
console.log(x);
var x = 10;
console.log(x);
})();
var x = 5;
(function () {
var x;
console.log(x);
x = 10;
console.log(x);
})();
从这个答案中JavaScript 中变量的作用域是什么?