使用 cc.Class 声明类型
cc.Class 是一个很常用的 API,用于声明 Cocos Creator 中的类,为了方便区分,我们把使用 cc.Class 声明的类叫做 CCClass。
定义 CCClass
cc.Class,传入一个原型对象,在原型对象中以键值对的形式设定所需的类型参数,就能创建出所需要的类。
var Sprite = cc.Class({ name: "sprite"});
Sprite 变量。同时还将类名设为 “sprite”,类名用于序列化,一般可以省略。
实例化
Sprite 变量保存的是一个 JavaScript 构造函数,可以直接 new 出一个对象:
var obj = new Sprite();
判断类型
instanceof:
cc.log(obj instanceof Sprite); // true
构造函数
ctor 声明构造函数:
var Sprite = cc.Class({ ctor: function () { cc.log(this instanceof Sprite); // true }});
onLoad方法代替。实例方法
var Sprite = cc.Class({ // 声明一个名叫 "print" 的实例方法 print: function () { }});继承
extends实现继承:
// 父类var Shape = cc.Class();// 子类var Rect = cc.Class({ extends: Shape});父构造函数
继承后,CCClass 会统一自动调用父构造函数,你不需要显式调用。
var Shape = cc.Class({ ctor: function () { cc.log("Shape"); // 实例化时,父构造函数会自动调用, }});var Rect = cc.Class({ extends: Shape});var Square = cc.Class({ extends: Rect, ctor: function () { cc.log("Square"); // 再调用子构造函数 }});var square = new Square();以上代码将依次输出 “Shape” 和 “Square”。
声明属性” class=”reference-link”>声明属性
属性检查器 中,从而方便地在场景中调整属性值。
properties字段中,填写属性名字和属性参数即可,如:
cc.Class({ extends: cc.Component, properties: { userID: 20, userName: "Foobar" }});属性检查器 中看到你刚刚定义的两个属性: 在 Cocos Creator 中,我们提供两种形式的属性声明方法:
简单声明
在多数情况下,我们都可以使用简单声明。
- 当声明的属性为基本 JavaScript 类型时,可以直接赋予默认值:
properties: { height: 20, // number type: "actor", // string loaded: false, // boolean target: null, // object }
cc.Node,cc.Vec2等),可以在声明处填写他们的构造函数来完成声明,如:
properties: { target: cc.Node, pos: cc.Vec2, }
cc.ValueType时(如:cc.Vec2,cc.Color或cc.Rect),除了上面的构造函数,还可以直接使用实例作为默认值:
properties: { pos: new cc.Vec2(10, 20), color: new cc.Color(255, 255, 255, 128), }
- 当声明属性是一个数组时,可以在声明处填写他们的类型或构造函数来完成声明,如:
properties: { any: [], // 不定义具体类型的数组 bools: [cc.Boolean], strings: [cc.String], floats: [cc.Float], ints: [cc.Integer], values: [cc.Vec2], nodes: [cc.Node], frames: [cc.SpriteFrame], }
注意:除了以上几种情况,其他类型我们都需要使用完整声明的方式来进行书写。
完整声明
属性检查器 中的显示方式,以及属性在场景序列化过程中的行为。例如:
properties: { score: { default: 0, displayName: "Score (player)", tooltip: "The score of player", }}
score 属性设置了三个参数 default, displayName 和 tooltip。这几个参数分别指定了 score 的默认值为 0,在 属性检查器 里,其属性名将显示为:“Score (player)”,并且当鼠标移到参数上时,显示对应的 Tooltip。
下面是常用参数:
- default: 设置属性的默认值,这个默认值仅在组件第一次添加到节点上时才会用到
- type: 限定属性的数据类型,详见 CCClass 进阶参考:type 参数
- visible: 设为 false 则不在 属性检查器 面板中显示该属性
- serializable: 设为 false 则不序列化(保存)该属性
- displayName: 在 属性检查器 面板中显示成指定名字
- tooltip: 在 属性检查器 面板中添加属性的 Tooltip
属性参数
数组声明
[],如果要在 属性检查器 中编辑,还需要设置 type 为构造函数,枚举,或者cc.Integer,cc.Float,cc.Boolean和cc.String。properties: { names: { default: [], type: [cc.String] // 用 type 指定数组的每个元素都是字符串类型 }, enemies: { default: [], type: [cc.Node] // type 同样写成数组,提高代码可读性 },}
get/set 声明
在属性中设置了 get 或 set 以后,访问属性的时候,就能触发预定义的 get 或 set 方法。定义方法如下:
>properties: { width: { get: function () { return this._width; }, set: function (value) { this._width = value; } }}
访问节点和其他组件 或 CCClass 进阶参考。
