[英]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
一点指向两个不同的东西,所以你必须至少使用其中一个变量。 默认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.