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/
thisin another variable: jsfiddle.net/ZghRv/2thatfor any subsequent references tothis?thisis what originated the event, e.g. the clicked element)thisto 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.