Question

I have a class with a function which handles an event. But when the event listener calls the handler function the this keyword refers to the clicked element and not to the class. I would like to make the other variables / functions of the class visible from the handler function.

Have a look: http://jsfiddle.net/cy7uM/1/

(Use FireBug or some other debugger to see the console.log messages)

function Class(){
    this.hello = "Hello World";

    document.getElementById("c").addEventListener("click", this.clickHandler); //doesn't work when clicked
}

Class.prototype.clickHandler = function(){
    console.log(this);
    alert(this.hello);   
}

var myobj = new Class();

myobj.clickHandler(); //works
Was it helpful?

Solution

try

function Class(){
    this.hello = "Hello World";

    document.getElementById("c").addEventListener("click", this.clickHandler.bind(this));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top