模块化脚本

模块化。 如果你还不确定模块化究竟能做什么,模块化相当于:

  • include
  • using
  • import
  • <link> 模块化使你可以在 Cocos Creator 中引用其它脚本文件:
  • - Cocos Creator 中的 JavaScript 使用和 Node.js 几乎相同的 CommonJS 标准来实现模块化,简单来说:
  • 同步require 方法来引用其它模块
  • module.exports 为导出的变量 如果你还不太明白,没关系,下面会详细讲解。

    不论模块如何定义,所有用户代码最终会由 Cocos Creator 编译为原生的 JavaScript,可直接在浏览器中运行。

    require

    require 来访问。例如我们有一个组件定义在 Rotate.js

    1. // Rotate.jscc.Class({ extends: cc.Component, // ...});

    现在要在别的脚本里访问它,可以:

    1. var Rotate = require("Rotate");

    require 返回的就是被模块导出的对象,通常我们都会将结果立即存到一个变量(var Rotate)。传入 require 的字符串就是模块的文件名,这个名字不包含路径也不包含后缀,而且大小写敏感。

    require 完整范例

    SinRotate.js

    1. // 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 ToolsConsole 中 require 项目里的任意模块。

    定义模块

    定义组件

    Rotate.js
    1. // Rotate.jsvar Rotate = cc.Class({ extends: cc.Component, properties: { speed: 1 }, update: function () { this.transform.rotation += this.speed; }});
    当你在脚本中声明了一个组件,Cocos Creator 会默认把它导出,其它脚本直接 require 这个模块就能使用这个组件。

    定义普通 JavaScript 模块

    config.js
    1. // config.jsvar cfg = { moveSpeed: 10, version: "0.15", showTutorial: true, load: function () { // ... }};cfg.load();
    config 对象:
    1. // player.jsvar config = require("config");cc.log("speed is", config.moveSpeed);
    cfg 没有被导出。由于 require 实际上获取的是目标脚本内的 module.exports 变量,所以我们还需要在 config.js 的最后设置 module.exports = config
    1. // 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 默认是一个空对象({}),可以直接往里面增加新的字段。
    1. // foobar.js:module.exports.foo = function () { cc.log("foo");};module.exports.bar = function () { cc.log("bar");};
    1. // test.js:var foobar = require("foobar");foobar.foo(); // "foo"foobar.bar(); // "bar"
  • module.exports 的值可以是任意 JavaScript 类型。
    1. // foobar.js:module.exports = { FOO: function () { this.type = "foo"; }, bar: "bar"};
    1. // test.js:var foobar = require("foobar");var foo = new foobar.FOO();cc.log(foo.type); // "foo"cc.log(foobar.bar); // "bar"

    封装私有变量

    var 定义的局部变量,将无法被模块外部访问。我们可以很轻松的封装模块内的私有变量:
    1. // foobar.js:var dirty = false;module.exports = { setDirty: function () { dirty = true; }, isDirty: function () { return dirty; },};
    1. // test1.js:var foo = require("foobar");cc.log(typeof foo.dirty); // "undefined"foo.setDirty();
    1. // test2.js:var foo = require("foobar");cc.log(foo.isDirty()); // true

    循环引用

    属性延迟定义

    第三方模块引用

    第三方模块引用文档