欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

CocosCreator學(xué)習(xí)之模塊化腳本

 更新時(shí)間:2021年04月16日 15:14:33   作者:麥克煎蛋  
這篇文章主要介紹了Cocos Creator 模塊化腳本,想加深學(xué)習(xí)CocosCreator腳本的同學(xué),一定要看一下

Cocos Creator模塊化腳本

Cocos Creator 允許你將代碼拆分成多個(gè)腳本文件,并且讓它們相互調(diào)用。這個(gè)步驟簡(jiǎn)稱為 模塊化。

模塊化使你可以在 Cocos Creator 中引用其它腳本文件:

  • 訪問(wèn)其它文件導(dǎo)出的參數(shù)
  • 調(diào)用其它文件導(dǎo)出的方法
  • 使用其它文件導(dǎo)出的類型
  • 使用或繼承其它 Component

Cocos Creator 中的 JavaScript 使用和 Node.js 幾乎相同的 CommonJS 標(biāo)準(zhǔn)來(lái)實(shí)現(xiàn)模塊化,簡(jiǎn)單來(lái)說(shuō):

  • 每一個(gè)單獨(dú)的腳本文件就構(gòu)成一個(gè)模塊
  • 每個(gè)模塊都是一個(gè)單獨(dú)的作用域
  • 以 同步 的 require 方法來(lái)引用其它模塊
  • 設(shè)置 module.exports 為導(dǎo)出的變量

當(dāng)你在腳本中聲明了一個(gè)組件,Creator 會(huì)默認(rèn)把它導(dǎo)出,其它腳本直接 require 這個(gè)模塊就能使用這個(gè)組件。

// Rotate.js

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

var Rotate = require("Rotate");

var SinRotate = cc.Class({
    extends: Rotate,
    update: function (dt) {
        this.rotation += this.speed * Math.sin(dt);
    }
});

模塊里不單單能定義組件,實(shí)際上你可以導(dǎo)出任意 JavaScript 對(duì)象。假設(shè)有個(gè)腳本 config.js

// config.js - v2

var cfg = {
    moveSpeed: 10,
    version: "0.15",
    showTutorial: true,

    load: function () {
        // ...
    }
};
cfg.load();

module.exports = cfg;

現(xiàn)在如果我們要在其它腳本中訪問(wèn) cfg 對(duì)象:

// player.js

var config = require("config");
cc.log("speed is", config.moveSpeed);

module.exports 的默認(rèn)值:
當(dāng)你的 module.exports 沒(méi)有任何定義時(shí),Creator 會(huì)自動(dòng)優(yōu)先將 exports 設(shè)置為腳本中定義的 Component。如果腳本沒(méi)定義 Component 但是定義了別的類型的 CCClass,則自動(dòng)把 exports 設(shè)為定義的 CCClass。

導(dǎo)出變量

module.exports 默認(rèn)是一個(gè)空對(duì)象({}),可以直接往里面增加新的字段。

// 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"

以上就是CocosCreator學(xué)習(xí)之模塊化腳本的詳細(xì)內(nèi)容,更多關(guān)于CocosCreator模塊化腳本的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論