Search code examples
javascriptscopethisprototype

Get properties of object in its function when it called by HTMLElement.onclick event - javascript


I have a several HTML elements I wanted to handle onclick for. In javascript code I defined the prototype that have property name and function whoAreYou() that must be onclick handler. It looks like:

var Somebody = function(name) {
    this.name = name;
}
Somebody.prototype.whoAreYou = function() {
    console.log("I am " + this.name)
};

var somebody = new Somebody("Gary");
document.getElementById("somebody1").onclick = somebody.whoAreYou;

But this is refered to HTML element but not to somebody and instead of "I am Gary" it says "I am undefined".

It was working while whoAreYou was defined inside of constructor but I need inheritability. How can I access his name considering whoAreYou is moved to Somebody.prototype?


Solution

  • You can bind the context:

    document.getElementById("somebody1").onclick = somebody.whoAreYou.bind(somebody);
    

    or

    document.getElementById("somebody1").onclick = function() { 
      somebody.whoAreYou()
    };