1

I'd like to include an onclick event in a JavaScript class, but since onclick is a function inside of the class the this variable won't work properly.

How can I modify/output the this variable from the onclick function?

img = new image();

function image() {
    this.width = 400;
    this.height = 600;
    document.getElementById('button').onclick = function()
    {
        alert(this.width); // alerts undefined
    };
}

See JSfiddle here: http://jsfiddle.net/ZghRv/

5
  • 2
    Store the outer this in another variable: jsfiddle.net/ZghRv/2 Commented Sep 18, 2013 at 3:23
  • Would I need to use that for any subsequent references to this? Commented Sep 18, 2013 at 3:28
  • You only need that inside event handlers (inside them, this is what originated the event, e.g. the clicked element) Commented Sep 18, 2013 at 3:31
  • Just cache this to a variable and use it inside the handler. not a good idea to change the context inside the handler for a constant value define outside. Commented Sep 18, 2013 at 3:33
  • @PSL could you provide a jsfiddle? Commented Sep 18, 2013 at 3:51

2 Answers 2

1

You can use bind() to create a new function that will have this set to the object you pass to bind().

img = new image();

function image() {
    this.width = 400;
    this.height = 600;
    document.getElementById('button').onclick = (function()
    {
        alert(this.width); // alerts undefined
    }).bind(this);  // <---  Add bind() here to pick the value of 'this' inside onclick
}

Check out JavaScript Function bind for more info and interactive examples.

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

Comments

0

You can also give reference to the outer this

Updated Fiddle:

http://jsfiddle.net/ZghRv/3/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.