参考
示例
运行后,在3秒后调用方法myFunc。在myFunc中,调用了方法getCurTime。
image.png
import { _decorator, Component, Node, Vec3, absMax, Label } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('Test')
export class Test extends Component
{
start():void
{
console.info("~~~~~00:" + this.getCurTime());
// 3秒后执行
setTimeout(()=>this.myFunc(), 3000);
}
myFunc(): void
{
console.info("~~~~~11:" + this.getCurTime());
}
getCurTime(): string
{
const date = new Date();
const str = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
return str;
}
}
使用说明
- 参数单位是毫秒,不是秒。
- 它的this是window,所以传递要执行的方法时,不能写成
setTimeout(this.myFunc, 3000);
报错信息
因为myFunc中调用了自己this中的方法getCurTime,当window作为this时,window中并没有getCurTime这个方法。
要写成
setTimeout(()=>this.myFunc(), 3000);
对于箭头函数中的 this,其指向直接包含此箭头函数定义的函数所属的对象。
网友评论