Skip to content

Comment on Map JavaScript APIparent

Comments

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().

Totally. 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.

Is 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.

ES6: no me, no bind.

element.addEventListener('click', e => this.foo(), false);

What 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.

Make the callback take another argument?

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.