按自定义类javascript

时间:2017-10-15 13:08:08

标签: javascript

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

如何访问主要城市元素和城市的另一个元素

1 个答案:

答案 0 :(得分:0)

您的问题是this中的 alert(this.city) 实际上是指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 } 引用你的功能。这有三种方式:

使用 .bind(this)

this

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);
    };
}

使用Arrow function

mouseover

PS:您也不太可能想要使用mouseenter - 因为它与{{1}}的工作方式完全不同。