繁体   English   中英

从ES6中的函数表达式访问类范围

[英]Accessing class scope from function expression in ES6

为了简化我的问题,我最初写出了一个事实上确实起作用的问题。 所以让我假设我有一个在ES6类中使用D3的代码:

export default class MyClass{
    constructor(){
        this.radius = 1;
    }
    myFunc(){
        this.tooltip //defined elsewhere in the class don't worry about it
            .on('mouseover', function(){
                d3.select(this).transition()
                    .ease('elastic')
                    .duration('250')
                    .attr('r', this.radius*1.5);
                    //keyword this has now been overridden
            });
    }
}

但是我如何实现上述功能,还是应该采用不同的方法?

回答问题的第一次修订

this在事件处理是一样的thismyFunc方法,但这没有关系的类。 回调是一个箭头功能 ,就是这样。 (代码中没有函数表达式)。

但是我如何实现上述功能,还是应该采用不同的方法?

您已经在实现所需的功能,不应该采取不同的方法。

现在,看看新问题,这仍然与课程无关。

但是我怎样才能实现所需的功能呢?

你不能this一点指向两个不同的东西,所以你必须至少使用其中一个变量。 默认var that = this方法仍然有效:

myFunc(){
    var that = this;
    this.tooltip.on('mouseover', function(e){
         d3.select(this).transition()
            .ease('elastic')
            .duration('250')
            .attr('r', that.radius*1.5);
    });
}

(您也可以使用var radius = this.radius;如果它不会改变直到mouseover事件)。

或者您使用event.currentTarget

myFunc(){
    this.tooltip.on('mouseover', (e) => {
         d3.select(e.currentTarget).transition()
            .ease('elastic')
            .duration('250')
            .attr('r', this.radius*1.5);
    });
}

你甚至将二者结合起来,不使用this根本,因为它可能会造成混乱它做什么参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM