by willvarfar · 14y ago · 0 comments
obj = {
get_name = function() { return "I am an object" },
func = function() { alert(this.get_name()); }
}
This looks dandy, and obj.func() works as expected.but if you pass obj.func as a callback, the this when its invoked will be some other object (by default, the window object):
button.onclick = obj.func; // bang when invoked
The number of times I got screwed by that. You end up having to have little anonymous functions for all callbacks: button.onclick = function(evt) { obj.func(); }
(apologies for bugs; just typing javascript from memory)(would love to be wrong)
tldr: JavaScript has functions, not methods :)
I do however intend to use an example similar to the one you have presented when I cover closures and scoping in JavaScript.
https://developer.mozilla.org/en-US/docs/JavaScript/Referenc...
button.onclick = obj.func.bind(obj);
So un-DRY! It's almost admirable, how blatant a hack this is.