[英]how can I access the variables of my current component in angular without using “this”
This question will sound a bit odd, but I will explain the reason. 这个问题听起来有点奇怪,但我会解释原因。 I am using d3.js combined with Angular.
我正在将d3.js与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.
一切都很好,但是在d3.js的逻辑内有时会发生一些事件,其中“ this”是与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 这是我使用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
: 注释说明您可以使用另一种语法来访问
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: 如果你真的想保持一些语法,我不建议,你可以存储
this
另一个变量:
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. 尝试使用var / let / const关键字将变量放置在类范围之外。 you could than try and access the variable without "this"
您可以尝试使用不带“ this”的变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.