由定制类的元素得到自定义类的JavaScript
问题描述:
function city(circle,reinf)
{
this.reinf = reinf;
this.circle.onmouseover = function(){
alert(this.city);
}
}
如何进入主城的元素和城市的另一个元素由定制类的元素得到自定义类的JavaScript
答
你的问题是,在alert(this.city)
this
实际上指的是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
}
在可变
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
完全不同。