CocosCreator模块化

模块化脚本

  • Cocos Creator 中的 JavaScript 使用和 Node.js 几乎相同的 CommonJS 标准来实现模块化,简单来说:
    • 每一个单独的脚本文件就构成一个模块
    • 每个模块都是一个单独的作用域
    • 以同步的 require 方法来引用其它模块
    • 设置 module.exports 为导出的变量

定义、引用模块

  • 每一个单独的脚本文件就是一个模块。当你在脚本中声明了一个组件,Creator 会默认把它导出,其它脚本直接 require 这个模块就能使用这个组件。
// Rotate.js

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

// SinRotate.js

var Rotate = require("Rotate");

var SinRotate = cc.Class({
    extends: Rotate,
    update: function (dt) {
        this.rotation += this.speed * Math.sin(dt);
    }
});
  • 如果在一个脚本中定义了很多模块,就需要用 module.exports 将其暴露。
  • 和微信小程序里面一样,本人习惯用 module.exports.functionName = functionName 的方式统一导出模块。
//Fruit.js

var Fruit = cc.Class({
	extends: cc.Component,
	...
})
var Apple = cc.Class({
	extends: Fruit,
	···
})
var Orange = cc.Class({
	extends: Fruit,
	...
})

module.exports.Apple = Apple;
module.exports.Orange = Orange;

// main.js

var myFruit = require('Fruit');

var myApple = myFruit.Apple();
var myOrange = myFruit.Orange();
  • 这种写法的原理是:module.exports 是一个空对象,我们导出时,等号左边的 Apple 是指新建一个对象 Apple,等号后面的 Apple 是指这个属性的值是 js 文件中的Apple
  • 我们发现,这样做还达到了封装私有变量的目的。如果我们不去暴露 Fruit 这个类,我们在外部就不能访问这个类。

猜你喜欢

转载自blog.csdn.net/qq_43575267/article/details/88911009
今日推荐