【问题标题】:Accessing class scope from function expression in ES6从 ES6 中的函数表达式访问类范围
【发布时间】:2016-08-13 03:43:12
【问题描述】:

为了简化我的问题,我最初写了一个确实有效的问题。所以让我们假设我有这个在 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
            });
    }
}

但是我怎样才能实现上述功能,或者我应该采取不同的方法?

【问题讨论】:

  • 没有“类范围”之类的东西。什么意思?

标签: javascript class scope ecmascript-6


【解决方案1】:

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

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

您不能让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,因为它可能会混淆它所指的内容。

【讨论】:

    【解决方案2】:

    回复first revision of the question

    您的事件处理程序中的thismyFunc 方法中的this 相同,但这与类无关。回调是arrow function,仅此而已。 (您的代码中没有函数表达式)。

    但是我怎样才能实现上述功能,或者我应该采取不同的方法?

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

    【讨论】:

    • 当他使用箭头函数时一切都会好起来的,在这种情况下他会得到undefined
    • @The:如果他使用函数表达式而不是箭头函数,this 将引用 jQuery 传递给处理程序的 #selector 元素。
    • 可能我的例子有问题,但你可以检查一下,当我点击按钮时,我得到undefined。我知道 jQuery 内部的事件处理程序 this 引用了它被触发的元素。 fiddle
    • @The:this是按钮,this.myvar当然是未定义的。
    • @Bergi 我实际上使用的是 D3 而不是 Jquery,但差异相同(请参阅更新的问题)-但您所描述的正是我的问题。
    猜你喜欢
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多