关于schedule 回调函数中找不到this的疑惑

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,如果想给回调函数里传别的参数应该怎么做?

拜谢各位大神:pray:

1: 我不是很确定 可以试试 move(){},
2: target是啥
3: 我通常是这么绑定参数
this.schedule(this.move.bind(this,arg1,arg2),delay)
不过不少人 用bind原生 会报错 至今不知道正确姿势是啥

//应该这样
start: function() {
var self = this;
//schedule里的this不是start方法传进来的this
this.schedule(self.move, 3);
},

//不过我建议你这么写,要不然你在unschedule时也会出错
start: function() {
this.movefunc = this.move.bind(this);
this.schedule(this.movefunc, 3);
//这样才能正常停止move方法
}

因为你用箭头函数定义了move方法。箭头函数会保持当前上下文的this,也就是你定义cc.Class()处的this,而非该cc.Class的实例。箭头函数你用bind绑定this也没用,类方法应该写成

move() {
    const r ...
}
// 或者
move: function() {
    const r ...
}


多谢!顺便求问这两张图是哪个帖子里的吗?

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