简体   繁体   中英

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, eg 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?

如果您需要某种模块化,则可以使用简单的模块模式,或者使用一些诸如RequireJSCommonJS模块其他实现的帮助程序库。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM