通过自定义类javascript的元素获取自定义类
如何访问主要城市元素和城市的另一个元素您的问题是通过自定义类javascript的元素获取自定义类,javascript,Javascript,如何访问主要城市元素和城市的另一个元素您的问题是警报(this.city)中的此实际上指的是此.circle单击的元素-因此您需要在函数中控制此引用。这里有三种方法: 使用 function city(circle,reinf) { this.reinf = reinf; this.circle.onmouseover = function(){ alert(this.city);
警报(this.city)
中的此
实际上指的是此.circle
单击的元素-因此您需要在函数中控制此
引用。这里有三种方法:
使用
function city(circle,reinf)
{
this.reinf = reinf;
this.circle.onmouseover = function(){
alert(this.city);
}
}
使用
功能城市(圆形,reinf){
this.city=“Foo”;
这个圆=圆;
this.reinf=reinf;
this.circle.onmouseinter=()=>{//
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
}
}
function city(circle, reinf) {
this.city = "Foo";
this.circle = circle;
this.reinf = reinf;
this.circle.onmouseenter = () => { // << Arrow function with unbound this
alert(this.city);
};
}