version:1.4.2
我先写了下面这段代码是ok的:
// use this for initialization
start: function() {
this.schedule(() => {
const r = Math.random();
if (r < 0.5) {
this._vx = (Math.random() - 0.5) * this.speed;
this._vy = (Math.random() - 1) * this.speed;
this._isMoving = true;
} else {
this._isMoving = false;
}
}, 3);
},
之后我把回调函数抽出来放到外面:
move: () => {
const r = Math.random();
console.log(this)
if (r < 0.5) {
this._vx = (Math.random() - 0.5) * this.speed;
this._vy = (Math.random() - 1) * this.speed;
this._isMoving = true;
} else {
this._isMoving = false;
}
},
// use this for initialization
start: function() {
this.schedule(this.move, 3);
},
就报错找不到this了,错误栈如下,顺带concole.log处输出的确实是undefined, 打断点进去明明能看到this存在
发生未经处理的异常: TypeErrorTypeError: Cannot set property '_isMoving' of undefinedTypeError: Cannot set property '_isMoving' of undefined
at enemy.move (d:\cocos\workspace\holdthedoor\assets\Script\enemy.js:20:13)
at CallbackTimer.trigger (d:\cocos\workspace\holdthedoor\app\engine\cocos2d\core\CCScheduler.js:243:1)
at CallbackTimer.update (d:\cocos\workspace\holdthedoor\app\engine\cocos2d\core\CCScheduler.js:210:1)
at TheClass.update (d:\cocos\workspace\holdthedoor\app\engine\cocos2d\core\CCScheduler.js:498:1)
at TheClass.mainLoop (d:\cocos\workspace\holdthedoor\app\engine\cocos2d\core\CCDirector.js:1381:1)
at callback (d:\cocos\workspace\holdthedoor\app\engine\cocos2d\core\CCGame.js:560:1)
新接触cocos creator, js也就是入门级,不知道有没有大神能告诉我
1,应该怎么写才能让move方法里能找到正确的this?
顺便还想问一下
2,schedule 接口里的target我们在回调里能拿到吗?
3,如果想给回调函数里传别的参数应该怎么做?
拜谢各位大神


不是哪个帖子的,我自己前两天画的,你这个问题正好用到