由定制类的元素得到自定义类的JavaScript

问题描述:

function city(circle,reinf) 
     { 
      this.reinf = reinf; 
      this.circle.onmouseover = function(){ 
       alert(this.city); 
      } 
     } 

如何进入主城的元素和城市的另一个元素由定制类的元素得到自定义类的JavaScript

你的问题是,在alert(this.city)this实际上指的是this.circle点击的元素 - 因此你需要在您的功能中控制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 
} 

可变

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使用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:你也可能不想使用mouseover - 因为它的工作方式与mouseenter完全不同。