简体   繁体   English

javascript window.onload范围

[英]javascript window.onload scope

Can someone explain why the alert returns "undefined" instead of "hello"? 有人可以解释为什么警报返回“未定义”而不是“你好”?

window.onload = function() {  
    var a = 'hello';  
    alert(window.a);  
}

variable 'a' is not part of window in your context. 变量'a'不是您上下文中窗口的一部分。

a is scoped to the anonymous function you've assigned to onload. a的作用域是您分配给onload的匿名函数。

you COULD add a as a member of window if you wanted: 如果你愿意,你可以添加一个窗口成员:

window.onload = function() {  
    window.a = 'hello';  
    alert(window.a);  
}

but i'd suggest against doing so. 但我建议不要这样做。

"Named variables are defined with the var statement. When used inside of a function, var defines variables with function-scope." “命名变量是用var语句定义的。当在函数内部使用时,var定义带有函数范围的变量。” - ( source ) - ( 来源

To be accessible globally, and particularly to make a a member of the window object, alter your code in this way: 可访问全球范围内,特别是使a对中的一员window对象,改变这样的代码:

var a; // defined in the global scope
window.onload = function() {  
    a = 'hello'; // initialized
    alert(window.a);  
}

Or in this way: 或者以这种方式:

var b = 'world'; //defined and initialized in the global scope
window.onload = function() {  
    alert(window.b);  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM