3 ms·
Even today, you shouldn't need to write code like that. Just bind functions to the current scope. That looks something like this (imagine this code is in the co
by timothya 12y ago
Even today, you shouldn't need to write code like that. Just bind functions to the current scope. That looks something like this (imagine this code is in the context of some object):
element.addEventListener('click', function(e) {
this.foo();
}.bind(this), false);
Notice the call to "bind" which binds the click handler function to the current object, so that inside it can call this.foo().
- bshimmin 12y agoTotally. And if you do need to support older browsers without a native `bind`, Underscore is your friend. There's not been a need to write `var me = this` or similar for a long time (or ever, really) but unfortunately you do still see a lot of - even very recent - code littered with it.
- dcherman 12y agoIs it really unfortunate? It's a matter of opinion. I find a single `var self = this;` to be much more readable than many .bind(this) calls when you're several levels deep.
- mashlol 12y agoWhat if you need to access both the outer `this` and the inner `this`. I.e. you still want to get the context changed within the callback, but you also need to access the outer context.
- JetSpiegel 12y agoMake the callback take another argument?
- noiv 12y agoES6: no me, no bind. element.addEventListener('click', e => this.foo(), false);