gpt4 book ai didi

javascript - 从 ES6 中的函数表达式访问类作用域

转载 作者:行者123 更新时间:2023-11-28 06:07:05 24 4
gpt4 key购买 nike

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

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

最佳答案

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

But how can I achieve the desired functionality?

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

关于javascript - 从 ES6 中的函数表达式访问类作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com