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/

cbourn
  • 162
  • 3
  • 12

2 Answers2

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.

nkron
  • 19,086
  • 3
  • 39
  • 27
0

You can also give reference to the outer this

Updated Fiddle:

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

Pal Singh
  • 1,964
  • 1
  • 14
  • 29