开发者

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 开发者_JS百科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?


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


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.


There are frameworks to do that.

Try for example UIZE


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜