Polluting the Global Object.

You must Login before you can answer or comment on any questions.

I guess a pretty basic question, but I'm having trouble understanding "polluting the global object" - what does this mean / why is it important not to do it?

why is it better to do globals.tabs rather than just tabs?

//add a single variable to the global scope to which we may choose to
    //intentionally add items to
    var globals = {};
 
    //create a private scope to prevent further polluting the global object
    (function() {
        var AppTabGroup = require('ui/AppTabGroup').AppTabGroup,
            ListWindow = require('ui/ListWindow').ListWindow,
            AddWindow = require('ui/AddWindow').AddWindow;
 
        // Initialize local storage
        require('db').createDb();
 
        //create our global tab group   
        globals.tabs = new AppTabGroup(
            {

1 Answer

Accepted Answer

Hi Name (guessing this is not your real name though)

This is a very simply concept (once you know it), it basically means rather than having lots and lots and lots of variables;

var firstname = 'Name';
var lastname = 'Surname';
function fullname(firstname, lastname) {
    return firstname + ' ' + lastname;
}
You should have everything coming from a single point, like;
var app = {
  firstname: 'Name',
  lastname: 'Surname',
  fullname: function () {
    return app.firstname + ' ' + app.lastname;
  }
};
If you need to add variables after this has been created;
...
app.age = 40;
alert(app.age);
This way everything is nice and neat, and contained in one variable, sometimes refereed to as a NameSpace (but opinions vary).

Doing this means a you can have a very tidy set of variable and hopefully that means a better app due to less errors because of errant variables.

Also read up on CommonJS as this can help you to keep the scope of your variables restricted to specific functionality - amongst other benefits.

Your Answer

Think you can help? Login to answer this question!