CocosCreator中的脚本组件都是继承自Component组件,而Component中的与两个特别的函数constructor函数(构造函数)和destroy函数(构析函数或者销毁函数),其中constructor构造函数是tpyescript定义的,而typescript中没有构析函数的概念,所以destroy销毁函数是由引擎定义的,这两个函数都可以在脚本组件中重写。但是重写时可能会出现下面两个问题。
比如重写constructor构造函数时vscode报错:
"message": "当派生类包含初始化属性、参数属性或专用标识符时,“super” 调用必须是构造函数中用来引用 “super” 或 “this” 的第一个语句。",
重写destroy销毁函数可能CocosCreator会报错。
Error: [Scene] Overwriting 'destroy' function in 'myScript' class without calling super is not allowed. Call the super function in 'destroy' please.
翻译是 错误:[Scene]不允许在不调用super的情况下重写“myScript”类中的“destroy”函数。请调用“destroy”中的超级函数。
这两个问题牵扯到一个关于面向对象编程的知识点,在可以继承对象的面向对象编程语言,派生类在重写基类的构造函数和构析(销毁)函数时,要调用基类的构造函数或者构析(销毁)函数,而且构造和构析是有顺序的。在构造时,应当先是基类构造再到派生类构造;在构析(销毁)时应先是派生类构析在到基类构析。
在CocosCretor中调用基类的构造函数的方法是super();调用基类的销毁方法是super.destroy();
注意
如果调用顺序错误也可能会发生错误,比如下面这个脚本
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('myScript')
export class myScript extends Component {
public member:number = 0;
public constructor(){
this.member = 1;
/**
* 逻辑处理
*/
super();//错误,基类构造函数应在处理逻辑前调用
}
public destroy(): boolean {
super.destroy();//调用顺序错误,应在处理逻辑后调用
this.member = 0;
/**
* 逻辑处理
*/
return;
}
start() {
}
update(deltaTime: number) {
}
}
虽然有在重写的构造构析函数中调用基类的构造构析函数,但是因为顺序错误所以也会提示错误。
下面整个脚本是正确的调用方式
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('myScript')
export class myScript extends Component {
public member:number = 0;
public constructor(){
super();//正确,基类构造函数在派生类构造函数第一行调用
this.member = 1;
/**
* 逻辑处理
*/
}
public destroy(): boolean {
this.member = 0;
/**
* 逻辑处理
*/
return super.destroy();//正确,在返回时调用,注意如果不是在return处调用也会触发引擎的错误
//因为最后一行并不能保证是函数的最末尾,引擎会检测是否在return处调用;
}
start() {
}
update(deltaTime: number) {
}
}
这篇文章由恐惧的海怪原创,转载请注明出处。