[英]When to use scope resolution in javascript?
When I set the onload property I use 当我设置我使用的onload属性时
window.onload=initialize_page;
However, when I use undefined, which I understand is a window property I simply use: 但是,当我使用undefined时,我理解的是一个窗口属性,我只是使用:
undefined
How do I know when to scope properties? 我如何知道何时调整属性?
If I remove window from the first statement it works. 如果我从第一个语句中删除窗口就可以了。 I guess I've seen both in code here on SO, but which way is best practice?
我想我在这里的代码中看到了这两个,但哪种方式是最好的做法?
When you want to define a global variable, it's recommended to prefix window.
如果要定义全局变量,建议使用前缀
window.
, to prevent conflicts with local variables with the same name. ,以防止与具有相同名称的局部变量冲突。
For example, Rocket (at the OP's comments) suggested to use onload=initialize_page;
例如,Rocket(在OP的评论中)建议使用
onload=initialize_page;
instead of window.onload = ...
. 而不是
window.onload = ...
This will fail in the following case: 在以下情况下,这将失败:
function foo() {
var onload = "on load";
onload = initialise_page;
// What? Let's check:
alert(onload === window.onload); //false
}
foo();
If you encounter a variable, and don't know whether it's a global variable or not, you can use the following code to determine it: 如果遇到变量,并且不知道它是否是全局变量,则可以使用以下代码来确定它:
alert( 'somevar' in window ); //If true, then in global scope. If false, then not
alert( somevar === window.somevar); // Risky. If somevar is not an object, this
// comparison will also be true. Example:
// var local = 1;window.local=1;
// ^ They're equal by value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.