Javascript 从d3事件处理程序访问类函数

Javascript 从d3事件处理程序访问类函数,javascript,events,d3.js,es6-class,Javascript,Events,D3.js,Es6 Class,我尝试在d3应用程序中使用es6类。我有一个绑定到“drag”事件的事件处理程序,但我无法从事件处理程序中访问该类this是我的类,但当触发事件时,this是DOM元素 代码: class Point { constructor(croot, cx, cy, ccolor) { this.x = cx; this.y = cy; this.size = 5; this.draggable = true; t

我尝试在d3应用程序中使用es6类。我有一个绑定到“drag”事件的事件处理程序,但我无法从事件处理程序中访问该类<当我手动调用处理程序时,code>this是我的类,但当触发事件时,
this
是DOM元素

代码:

class Point {

    constructor(croot, cx, cy, ccolor) {
        this.x = cx;
        this.y = cy;
        this.size = 5;
        this.draggable = true;
        this.root = croot;
        this.color = ccolor;
        this.circle = this.root.append('circle')
            .attr('class', "draggable")
            .attr('r', this.size)
            .attr('fill', "white")
            .attr('stroke', this.color)
            .attr('stroke-width', 2)
            .call(d3.drag(this).on('drag', this.onDrag));
        this.circle.attr('transform',
            `translate(${(this.x + 0.5) * scale} ${(this.y + 0.5) * scale})`);
    }


    onDrag() {
        console.log(this);
        this.x = (d3.event.x / scale);
        this.y = (d3.event.y / scale);
        this.circle.attr('transform',
            `translate(${(this.x + 0.5) * scale} ${(this.y + 0.5) * scale})`);
    }

}

当您以这种方式传递函数时,就会松开对此的绑定。它将引用传递给D3调用的函数,因此调用上下文会发生变化。您可以通过显式绑定来保留此

call(d3.drag(this).on('drag', this.onDrag.bind(this))