javascript函数中的词法作用域,为什么代码返回undefined ?
Lexical Scoping in javascript function, why is the code returning undefined
var variable = "top level " ;
function outer(){
alert(variable); // why does this alert returns undefined ??
var variable = " inside outer, outside inner";
function inner(){
alert(variable);
}
inner();
}
outer();
我从词法作用域的定义中理解的是,函数可以访问其作用域内和以上的所有值,即在它们之前定义的所有值。那么,为什么第一个警报返回undefined呢?
这是因为提升,你在函数内声明的变量被提升到它所在作用域的顶部,所以你的代码看起来像这样
var variable = "top level " ;
function outer(){
var variable; // undefined, a new local variable is declared, but not defined
alert(variable); // alerts undefined, as that's what the variable is
variable = " inside outer, outside inner";
function inner(){
alert(variable);
}
inner();
}
outer();
如果您只想更改外部的variable
,请删除var
关键字,因为它声明了一个新的局部变量而不是
var variable = "top level " ;
function outer(){
alert(variable);
variable = " inside outer, outside inner"; // no "var"
function inner(){
alert(variable);
}
inner();
}
outer();
相关文章:
- 为什么忽略了eval()代码中的语法错误
- 为什么indexOf在这个js代码中不起作用
- 为什么我在这个javaScript代码中使用NaN
- 为什么此验证代码不起作用
- 我的jquery代码不起作用.为什么?
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- 我不知道为什么我的代码是错误的?又有什么错
- 为什么这个代码不能正常工作
- 为什么我的解析云代码请求'未经授权'
- 为什么不't我的ruby代码与javascript文件一起插入
- I'我不知道为什么我的代码没有'不起作用
- 为什么这个JS代码打印未定义
- 为什么这个代码没有定义,但没有2
- 为什么jQuery代码段在没有IFrame的情况下可以工作,而在有IFrame时却不能工作
- 为什么当async标志设置为false时,xmlhttprequest中的代码可以工作,而当它设置为true时却不能工作
- 为什么代码会指向window对象
- 为什么动态加载的事件在我的代码中不能正常工作
- 为什么我的.blur()代码只处理第二个模糊
- 为什么phantomjs代码没有't遍历数组
- 为什么Javascript程序员更喜欢在代码中重复字符串作为常量,而不是使用枚举类型的对象