Cocos Creator模塊化腳本
Cocos Creator 允許你將代碼拆分成多個腳本文件,并且讓它們相互調用。這個步驟簡稱為 模塊化。
模塊化使你可以在 Cocos Creator 中引用其它腳本文件:
- 訪問其它文件導出的參數
- 調用其它文件導出的方法
- 使用其它文件導出的類型
- 使用或繼承其它 Component
Cocos Creator 中的 JavaScript 使用和 Node.js 幾乎相同的 CommonJS 標準來實現模塊化,簡單來說:
- 每一個單獨的腳本文件就構成一個模塊
- 每個模塊都是一個單獨的作用域
- 以 同步 的 require 方法來引用其它模塊
- 設置 module.exports 為導出的變量
當你在腳本中聲明了一個組件,Creator 會默認把它導出,其它腳本直接 require 這個模塊就能使用這個組件。
1
2
3
4
5
6
|
// Rotate.js cc.Class({ extends: cc.Component, // ... });<span style= "font-family: "Courier New"; background-color: initial; color: rgb(0, 128, 0); line-height: 1.5 !important;" > SinRotate.js</span><br type= "_moz" > |
1
2
3
4
5
6
7
8
9
10
|
// SinRotate.js var Rotate = require( "Rotate" ); var SinRotate = cc.Class({ extends: Rotate, update: function (dt) { this .rotation += this .speed * Math.sin(dt); } }); |
模塊里不單單能定義組件,實際上你可以導出任意 JavaScript 對象。假設有個腳本 config.js
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// config.js - v2 var cfg = { moveSpeed: 10, version: "0.15" , showTutorial: true , load: function () { // ... } }; cfg.load(); module.exports = cfg; |
現在如果我們要在其它腳本中訪問 cfg 對象:
1
2
3
4
|
// player.js var config = require( "config" ); cc.log( "speed is" , config.moveSpeed); |
module.exports
的默認值:
當你的 module.exports
沒有任何定義時,Creator 會自動優先將 exports
設置為腳本中定義的 Component。如果腳本沒定義 Component 但是定義了別的類型的 CCClass,則自動把 exports
設為定義的 CCClass。
導出變量
module.exports
默認是一個空對象({}
),可以直接往里面增加新的字段。
1
2
3
4
5
6
7
8
|
// foobar.js: module.exports.foo = function () { cc.log( "foo" ); }; module.exports.bar = function () { cc.log( "bar" ); }; |
1
2
3
4
5
|
// test.js: var foobar = require( "foobar" ); foobar.foo(); // "foo" foobar.bar(); // "bar" |
module.exports
的值可以是任意 JavaScript 類型。
1
2
3
4
5
6
7
8
|
// foobar.js: module.exports = { FOO: function () { this .type = "foo" ; }, bar: "bar" }; |
1
2
3
4
5
6
|
// test.js: var foobar = require( "foobar" ); var foo = new foobar.FOO(); cc.log(foo.type); // "foo" cc.log(foobar.bar); // "bar" |
以上就是CocosCreator學習之模塊化腳本的詳細內容,更多關于CocosCreator模塊化腳本的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/mazhiyong/p/13745264.html