Jack
Jack

Reputation: 15872

How can I use JavaScript in a modular way, similar to Java classes?

I'm creating a JavaScript game, previously I've always created the whole game inside a single JavaScript file. I'd like to be able to reduce coupling by separating the code into modules. Is it possible to write JavaScript in one file that is accessible from another file, using some kind of include statement?

<script type="text/javascript" src="assets/scripts/asset_manager.js"></script>
<script type="text/javascript" src="assets/scripts/game.js"></script>

I'd like for the javascript files to act in a similar fashion to Javas classes, e.g. within the game.js file writing something like this.extends('asset_manager').

Edit: It looks like RequireJS and CommonJS are both good candidates, have you found any drawbacks or advantages of using either?

Upvotes: 2

Views: 189

Answers (4)

Adam Jurczyk
Adam Jurczyk

Reputation: 2131

If you want some modularity, you could simple module pattern, or some helper lib like RequireJS or other implementation of CommonJS modules.

Upvotes: 3

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11038

suppose in the file asset_manager you have something like

function AssetManager(){
    // some code here
}

now in game.js, to extend that class you have to do something like this

// define the new class
Game.prototype = new AssetManager()

function Game(){
    // Call super constructor.
    AssetManager.apply( this, arguments );
}

The "prototype" is a prebuilt object that simplifies the process of adding custom properties/ methods to all instances of an object

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

Look at CommonJS with asynchronous module definition. This is nodejs's require() with support for the web.

There are many implementations: http://www.commonjs.org/impl/

See http://requirejs.org/ for example.

Upvotes: 2

Petar Ivanov
Petar Ivanov

Reputation: 93030

There are frameworks to do that.

Try for example UIZE

Upvotes: 0

Related Questions