2017-10-15 11 views

答えて

0

あなたの問題は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を使用したくないと思われます。

関連する問題