Cocos Creator modular scripts
Cocos Creator allows you to split your code into multiple script files and make them call each other. This step is simply called modularity.
Modularity allows you to reference other script files in Cocos Creator:
- Access other file export parameters
- Call other file export methods
- Types of export using other files
- Use or inherit other Components
JavaScript in Cocos Creator uses nearly the same CommonJS standard to achieve modularity, simply put:
- Each individual script file forms a module
- Each module is a separate scope
- Refer to other modules using the synchronous require method
- Set as exported variable
When you declare a component in a script, Creator will export it by default, and other scripts can use this component directly by requiring the module.
// ({ extends: , // ... });
// var Rotate = require("Rotate"); var SinRotate = ({ extends: Rotate, update: function (dt) { += * (dt); } });
Components can be defined in modules, but you can actually export any JavaScript object. Suppose there is a script:
// - v2 var cfg = { moveSpeed: 10, version: "0.15", showTutorial: true, load: function () { // ... } }; (); = cfg;
Now if we want to access the cfg object in other scripts:
// var config = require("config"); ("speed is", );
Default value:
When yourCreator will automatically prioritize the
exports
Set as the Component defined in the script. If the script does not define Component, but defines another type ofCCClass, then automaticallyexports
Set as the defined CCClass.
Export variables
By default, it is an empty object (
{}
), you can add new fields directly into it.
// : = function () { ("foo"); }; = function () { ("bar"); };
// : var foobar = require("foobar"); (); // "foo" (); // "bar"
The value of the javascript type can be of any JavaScript type.
// : = { FOO: function () { = "foo"; }, bar: "bar" };
// : var foobar = require("foobar"); var foo = new (); (); // "foo" (); // "bar"
The above is the detailed content of the modular scripts learned by CocosCreator. For more information about CocosCreator modular scripts, please follow my other related articles!