废话不多说,先上代码:
const {ccclass, property} = cc._decorator;
@ccclass
export default class Countdown extends cc.Component {
@property(cc.Animation)
animation: cc.Animation = null;
@property(cc.Label)
labelComponent: cc.Label = null;
count: number = 0;
callback: Function = null;
// LIFE-CYCLE CALLBACKS:
onLoad () {}
start () {}
showTime (time: number) {
this.count = time;
this.animation.play();
this.callback = function () {
if (this.count <= 0) {
this.labelComponent.unschedule(this.callback);
return;
}
this.count--;
**this.labelComponent.string = this.count.toString();** // 访问组件需绑定响应函数调用者为this
}.bind(this)
this.labelComponent.schedule(this.callback, 1);
this.labelComponent.string = this.count.toString();
}
// update (dt) {}
}
问题出在这句:this.labelComponent.string = this.count.toString();
,如果想在this.callback 中设置 this.labelComponent.string,正确的用法是 this.callback = funtion () {}.bind(this)
,否则会报这样的错误:Uncaught TypeError: Cannot set property 'string' of undefined