あなたの問題はalert(this.city)
でthis
が実際にthis.circle
クリックされた要素を指していることである - あなたのため、関数内のthis
参照を制御する必要があります。 Arrow function
function city(circle, reinf) {
this.city = "Foo";
this.circle = circle;
this.reinf = reinf;
this.circle.onmouseenter =() => { // << Arrow function with unbound this
alert(this.city);
};
}
を使用して
変数
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
}
}
でthis
を保存.bind(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
}
を使用して
:ここでは3つの方法があります
PS:mouseenter
とはかなり異なるため、mouseover
を使用したくないと思われます。