Edgar Alexander
Edgar Alexander

Reputation: 374

Is this a good way to prevent namespace pollution in JavaScript?

I'm designing the structure of an HTML5 online videogame, and I want to use some namespaces in order to organize all my functions and classes, so this idea just came to me a few mins ago, but I don't know if it is the best:

(
    function () 
    {
        var xhr = new XMLHttpRequest();

        function load (file) 
        {
            xhr.open('GET', file, false);
            xhr.send();

            return xhr.responseText;
        }

        eval // Imported files
        (
            load('func.js') + 
            load('class.js')
        );

        function main () 
        {
            func();
            var instance = new Class();
            alert(instance.getMessage());
        }

        window.addEventListener('load', main, false);
    }
)();

func.js:

function func () 
{
    alert('This is an imported function.');
}

Class.js

function Class () 
{
    this.getMessage = function () 
    {
        return "This is an imported class.";
    }
}

I like this because it looks like the file import model from PHP, and I avoid so many verbose things when I need to call each function, but I'm not that sure, what do you think about it?

Upvotes: 0

Views: 623

Answers (1)

Tarwin Stroh-Spijer
Tarwin Stroh-Spijer

Reputation: 353

I would suggest using an already implemented model such as RequireJS. This handles loading of JS files and modulization of code into class like structures. It also comes with the added benefit of a host of utilities that let you merge files for production, which is great as you generally want less number of files loaded over HTTP for speed.

With the example above you still have the problem of polluting your global namespace. A good way to not do this would be as follows:

(function(){

  // private
  var thoughts = 'meow';
  var say = function(sound) {
    console.log(thoughts);
  };

  // public
  var feet = ['left', 'right'];
  var talk = function(){
    say(thoughts);
  };

  // expose
  window.cat = {
    talk: talk,
    feet: feet
  };

}()); // self running function

console.log('My cat has ' + cat.feet.length + ' feet');
console.log(cat.talk);

Upvotes: 3

Related Questions