function city(circle,reinf)
{
this.reinf = reinf;
this.circle.onmouseover = function(){
alert(this.city);
}
}
如何访问主要城市元素和城市的另一个元素
答案 0 :(得分:0)
您的问题是this
中的 alert(this.city)
实际上是指this.circle
点击的元素 - 因此您需要控制this
内的function city(circle, reinf) {
this.city = "Foo";
this.circle = circle; // Forgot this one?
this.reinf = reinf;
this.circle.onmouseenter = function(){
alert(this.city);
}.bind(this); // << bind to the outer this context
}
引用你的功能。这有三种方式:
使用 .bind(this)
this
将function city(circle, reinf) {
var self = this;
this.city = "Foo";
this.circle = circle;
this.reinf = reinf;
this.circle.onmouseenter = function(){
alert(self.city); // << refer to self
}
}
存储在变量
function city(circle, reinf) {
this.city = "Foo";
this.circle = circle;
this.reinf = reinf;
this.circle.onmouseenter = () => { // << Arrow function with unbound this
alert(this.city);
};
}
mouseover
PS:您也不太可能想要使用mouseenter
- 因为它与{{1}}的工作方式完全不同。