0

I want to assign onclick event listener to an object from within a class and then get some variable from the instance that created that onclick

function myclass() {

    this.myvar;

    this.myfunc = function() 
    {
        alert(this.myvar);
        document.onmousedown = this.mouseDown;        
    }

    this.mouseDown = function(e) 
    {
        alert(this.myvar); //does not work of course
        //how could I access myvar from current myclass instance
    }

}


var myclass_instance = new myclass();
    myclass_instance.myvar = 'value'
    myclass_instance.myfunc();

http://jsfiddle.net/E7wK4/

4

2 回答 2

1

thismouseDown事件不是this实例的情况下。

试试这个

function myclass() {

    var _this = this;

    this.myvar;

    this.myfunc = function() 
    {
        alert(this.myvar);
        document.onmousedown = this.mouseDown;        
    }

    this.mouseDown = function(e) 
    {
        alert(_this.myvar); //<<<<
    }

}

演示:http: //jsfiddle.net/maniator/E7wK4/1/

于 2013-07-22T17:55:43.520 回答
1

作为@Neal 的替代方案,您可以绑定它。

document.onmousedown = this.mouseDown.bind(this);
于 2013-07-22T17:57:33.217 回答