myElem.onclick = myObjGlobal.func2;
This doesn't do what you think inn JavaScript. It doesn't give you func2
with the object "attached" to it in any way; it just gives you func2
. When it gets called later, it's called as a method of myElem
, so that's what this
is.
This is a gigantic and awful wart in JS. :)
You can either wrap it in another function:
myElem.onclick = function() {
myObjGlobal.func2();
};
Or use .bind
, which does effectively the same thing, and which is supported almost universally nowadays:
myElem.onclick = myObjGlobal.func2.bind(myObjGlobal);
Note also that assigning to onclick
is a little rude, since you'll clobber any existing click handler. You may want addEventListener
instead.