模块化脚本
模块化。 如果你还不确定模块化究竟能做什么,模块化相当于:
includeusingimport<link>模块化使你可以在 Cocos Creator 中引用其它脚本文件:- - Cocos Creator 中的 JavaScript 使用和 Node.js 几乎相同的 CommonJS 标准来实现模块化,简单来说:
- 同步的
require方法来引用其它模块 module.exports为导出的变量 如果你还不太明白,没关系,下面会详细讲解。不论模块如何定义,所有用户代码最终会由 Cocos Creator 编译为原生的 JavaScript,可直接在浏览器中运行。
引用模块” class=”reference-link”>引用模块
require
require来访问。例如我们有一个组件定义在Rotate.js:// Rotate.jscc.Class({ extends: cc.Component, // ...});
现在要在别的脚本里访问它,可以:
var Rotate = require("Rotate");
require返回的就是被模块导出的对象,通常我们都会将结果立即存到一个变量(var Rotate)。传入require的字符串就是模块的文件名,这个名字不包含路径也不包含后缀,而且大小写敏感。require 完整范例
SinRotate.js:// SinRotate.jsvar Rotate = require("Rotate");var SinRotate = cc.Class({ extends: Rotate, update: function (dt) { this.rotation += this.speed * Math.sin(dt); }});
update方法进行了重写。require("SinRotate")。 备注:require可以在脚本的任何地方任意时刻进行调用。- Developer Tools 的 Console 中 require 项目里的任意模块。
定义模块
定义组件
Rotate.js:
当你在脚本中声明了一个组件,Cocos Creator 会默认把它导出,其它脚本直接 require 这个模块就能使用这个组件。// Rotate.jsvar Rotate = cc.Class({ extends: cc.Component, properties: { speed: 1 }, update: function () { this.transform.rotation += this.speed; }});
定义普通 JavaScript 模块
config.js// config.jsvar cfg = { moveSpeed: 10, version: "0.15", showTutorial: true, load: function () { // ... }};cfg.load();
config对象:// player.jsvar config = require("config");cc.log("speed is", config.moveSpeed);
cfg没有被导出。由于 require 实际上获取的是目标脚本内的module.exports变量,所以我们还需要在config.js的最后设置module.exports = config:// config.js - v2var cfg = { moveSpeed: 10, version: "0.15", showTutorial: true, load: function () { // ... }};cfg.load();module.exports = cfg;
player.js便能正确输出:”speed is 10”。exports? 因为 Component 是 Cocos Creator 中的特殊类型,如果一个脚本定义了 Component 却没有声明exports,Cocos Creator 会自动将exports设置为 Component。 备注: module上增加的其它变量是不能导出的,也就是说exports不能替换成其它变量名,系统只会读取exports这个变量。更多示例
导出变量
module.exports默认是一个空对象({}),可以直接往里面增加新的字段。// foobar.js:module.exports.foo = function () { cc.log("foo");};module.exports.bar = function () { cc.log("bar");};
// test.js:var foobar = require("foobar");foobar.foo(); // "foo"foobar.bar(); // "bar"
module.exports的值可以是任意 JavaScript 类型。// foobar.js:module.exports = { FOO: function () { this.type = "foo"; }, bar: "bar"};
// test.js:var foobar = require("foobar");var foo = new foobar.FOO();cc.log(foo.type); // "foo"cc.log(foobar.bar); // "bar"
封装私有变量
var定义的局部变量,将无法被模块外部访问。我们可以很轻松的封装模块内的私有变量:// foobar.js:var dirty = false;module.exports = { setDirty: function () { dirty = true; }, isDirty: function () { return dirty; },};
// test1.js:var foo = require("foobar");cc.log(typeof foo.dirty); // "undefined"foo.setDirty();
// test2.js:var foo = require("foobar");cc.log(foo.isDirty()); // true
循环引用
属性延迟定义第三方模块引用
第三方模块引用文档
