ES6将参数传递给从回调函数调用的函数

ES6 Pass paremeter to function which called from callback function

本文关键字:函数调用 函数 回调 参数传递 ES6      更新时间:2023-09-26

我正试图将参数传递给回调函数中调用的函数,这是否可能与es6或javascript?下面是示例:

   sprite.on('mousedown', this.onDragStart)
         .on('touchstart', this.onDragStart)
         .on('mouseup', this.onDragEnd)
         .on('mouseupoutside', this.onDragEnd)
         .on('touchend', this.onDragEnd)
         .on('touchendoutside', this.onDragEnd)
         .on('mousemove', this.onDragMove);
         .on('touchmove', this.onDragMove);

   onDragStart(event) {
           this.data = event.data;
           this.alpha = 0.5;
           this.dragging = true;
           this.selected  = true;
       }
    onDragMove(arg) {
        if (this.dragging) {
            var newPosition = this.data.getLocalPosition(this.parent);
            arg.m_orange.setPosition(newPosition.x, newPosition.y);
        }
    }
    onDragEnd() {
        this.alpha = 1;
        this.dragging = false;
        this.data = null;
        this.selected = false;
    }

我想传递一个参数函数onDragMove,这是调用只有当鼠标移动,这是可能的吗?

如果没有,有没有其他方法传递父类的关键字this到onDragMove函数?

你也可以使用es6的箭头函数来代替bind。

on('mousemove', (ev) => this.onDragMove(ev, otherArg))

你可以使用Function.prototype.bind:

on('mousemove', this.onDragMove.bind(thisArg, otherArg))