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

时间:2016-04-20 12:43:30

标签: javascript class scope ecmascript-6

为了简化我的问题,我最初写出了一个实际上有效的问题。因此,假设我有一个在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
            });
    }
}

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

2 个答案:

答案 0 :(得分:0)

回答first revision of the question

事件处理程序中的thisthis方法中的myFunc相同,但这与类无关。回调是arrow function,这就是全部。 (代码中没有函数表达式。)

  

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

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

答案 1 :(得分:0)

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

  

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

您无法this指向两个不同的内容,因此您必须至少使用其中一个变量。 default var that = this approach仍然运作良好:

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;。)

或者您使用event.currentTarget

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

或者你甚至将两者结合起来并且根本不使用this,因为它可能会引起混淆。