Ihr Problem ist, dass this
in alert(this.city)
bezieht sich eigentlich auf das Element this.circle
geklickt - damit Sie müssen die this
Referenz innerhalb Ihrer Funktion steuern. Hier sind drei Möglichkeiten:
Mit .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
}
Speichern this
in einer Variable
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
}
}
Mit 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);
};
}
PS: Sie werden wahrscheinlich auch nicht mouseover
verwenden - da es ziemlich anders als mouseenter
funktioniert.