0

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?

2
  • 2
    You don't need eval. This doesn't seem like good practice. Look into RequireJS and Browserify. Commented Jan 31, 2014 at 23:59
  • Hey, thank's for your comment, I'm working on it :) Commented Feb 1, 2014 at 0:08

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.