简体   繁体   中英

When to use scope resolution in javascript?

When I set the onload property I use

window.onload=initialize_page;

However, when I use undefined, which I understand is a window property I simply use:

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. , to prevent conflicts with local variables with the same name.

For example, Rocket (at the OP's comments) suggested to use onload=initialize_page; instead of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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