I have a code like this:
var Obj = {
el : document.getElementById("elementId"),
doSomething : function(){ this.el.property = "value" }
};
Obj.el.addEventListener('click', Obj.doSomething);
but the element this.el is undefined when the click event is fired ?
What causes this to happen?
NOTE: I don’t know how to break the lines in the code in this editor, that’s why it’s in a single line.
In JavaScript (unlike most other languages with similar syntax),
thisis defined entirely by how a function is called, not where it’s defined. The way event handlers are called,thiswithin your function doesn’t refer to your object.You can correct it in three ways:
If you’re targeting ES5-enabled browsers or including an ES5 “shim”, use
Function#bind:Otherwise, use a closure:
As RobG pointed out in the comments, because you have only one
Objobject (rather than having a constructor function or something that will create more than one as necessary), you could just refer to that object using its variable (Obj) rather thanthis:That only works when the object is a one-off within the scope in which it’s defined (which is true for your
Objexample). If the only reference you have to it werethis(e.g., you didn’t haveObj), you couldn’t do this and would want one of the prior two options.More:
thisNote that your
elproperty is suspect, though. You’ve defined it as…which means that
elnow points to the functiongetElementById. That’s probably not what you meant to do. Presumably you meantelto refer to a DOM element that you retrieved viagetElementById, e.g.:More here.