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/

1
  • 1
    What is it not doing that you expected it to do? Commented Jul 22, 2013 at 17:54

2 Answers 2

1

this in the mouseDown event is not the this of the instance.

Try this instead:

function myclass() {

    var _this = this;

    this.myvar;

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

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

}

Demo: http://jsfiddle.net/maniator/E7wK4/1/

Sign up to request clarification or add additional context in comments.

Comments

1

As an alternative to @Neal you could bind this.

document.onmousedown = this.mouseDown.bind(this);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.