This question will sound a bit odd, but I will explain the reason. I am using d3.js combined with Angular. everything is fine, but sometimes there are events within the logic of d3.js in which "this" is a different value from the context of angular. For this reason I would like to know if there is a way to directly access the variables that I have defined in my component in the style of:
HomeComponent.myVar //HomeComponent name of my current component
Instead of
this.myvar
this is a example of my problem using d3.js
Node.on("mouseout", unfocus);
function unfocus(){
console.log(this); //problem context angular
}
Node.mouseover(function(d){
console.log(this); //this is not context angular, is a value of this event
console.log(HomeComponent.myvar); //not works, but is my idea
})
thank you.
The comments explain that you can use another syntax to still be able to access this
:
Node.mouseover(d => {
console.log(this);
})
If you really want to keep the other syntax, which I don't recommend, you can store this
in another variable:
let self = this;
Node.mouseover(function(d){
console.log(self);
})
I don't recommend it because it's harder to understand, it's error prone, and it's not always clear what the scope of the variable is.
try placing your variables outside of the class' scope with a var/let/const keyword. you could than try and access the variable without "this"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.