简体   繁体   中英

JavaScript: is there any advantage in wrapping everything in a variable?

I've seen several times the following JS coding style:

document.addEventListener("DOMContentLoaded", function() {
    foo.run();
});

var foo = {
    bar: null,
    baz: null,

    run: function() {
        foo.init();
    },
    init: function() {
        foo.bar = 1;
    }
    ...
};

So basically everything except addEventListener is wrapped in a JS object. Is this any good? Why?

Doing this (and also with functions instead of objects, as that gives you local scope) avoids putting to much stuff into the global namespace where it may conflict with other things.

That is especially important if you want to have modular, re-usable code (where you don't know that the application you are being dropped in to doesn't already make use of window.init or window.bar .

Basically, this is the same "global variables are bad" discussion you can have in any language.

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