項目鏈接:https://github.com/cocos-creator/tutorial-first-game/tree/master/polished_project_es6
1.import加載模塊
//Game.js
import Player from "./Player";
import ScoreFX from "./ScoreFX";
import Star from "./Star";
// Player.js
export default class NewScript extends cc.Component{}
在Player.js中, export default命令爲模塊指定默認輸出,導出對外默認類——NewScript, 類名NewScript也是可以省略的
Game.js加載該模塊時,import命令可以爲該默認類指定任意名字——Player。需要注意的是,這時import命令後面,不使用大括號
2.const {ccclass, property} = cc._decorator
// Game.js
const {ccclass, property} = cc._decorator;
這是CommonJS的語法,const加一對大括號,大括號裏用兩個變量去接收cc._decorator模塊的兩個輸出變量。大括號裏面的變量名,必須與被導入模塊(cc._decorator)對外接口的名稱相同
_decorator 模塊:一些 JavaScript 裝飾器,目前可以通過 “cc._decorator” 來訪問。 (這些 API 仍不完全穩定,有可能隨着 JavaScript 裝飾器的標準實現而調整)
3.@ccclass
@ccclass
export default class NewScript extends cc.Component { }
ccclass(); 將標準寫法的 ES6 Class 聲明爲 CCClass
const {ccclass} = cc._decorator;
// define a CCClass, omit the name
@ccclass
class NewScript extends cc.Component {
// ...
}
// define a CCClass with a name
@ccclass('LoginData')
class LoginData {
// ...
}
4.@property
property(); 定義 CCClass 所用的屬性
const {ccclass, property} = cc._decorator;
@ccclass
class NewScript extends cc.Component {
@property({
type: cc.Node
})
targetNode1 = null;
@property(cc.Node)
targetNode2 = null;
@property(cc.Button)
targetButton = null;
@property
_width = 100;
@property
get width () {
return this._width;
}
@property
set width (value) {
this._width = value;
}
@property
offset = new cc.Vec2(100, 100);
@property(cc.Vec2)
offsets = [];
@property(cc.SpriteFrame)
frame = null;
}
上面的代碼相當於
var NewScript = cc.Class({
properties: {
targetNode1: {
default: null,
type: cc.Node
},
targetNode2: {
default: null,
type: cc.Node
},
targetButton: {
default: null,
type: cc.Button
},
_width: 100,
width: {
get () {
return this._width;
},
set (value) {
this._width = value;
}
},
offset: new cc.Vec2(100, 100)
offsets: {
default: [],
type: cc.Vec2
}
frame: {
default: null,
type: cc.SpriteFrame
},
}
});
5.getComponent()
node.getComponent();
獲取節點上指定類型的組件,如果節點有附加指定類型的組件,則返回,如果沒有則爲空。
傳入參數也可以是腳本的名稱
newStar.getComponent(Star).init(this);
6.extends cc.Component
Component 類型:所有附加到節點的基類
注意:不允許使用組件的子類構造參數,因爲組件是由引擎創建的