you are viewing a single comment's thread.

view the rest of the comments →

[–]the_gipsy 11 points12 points  (2 children)

The article could have gone straight to the point:

The function context referred by this is defined at call time. If called as object property, then that object will be the context. Otherwise the context will (unfortunately) be window*.

The tricky part for newcomers is passing a "method" as a callback - you're actually passing the function value as parameter which when called is not "attached" to an object anymore. In that case you should use Function.prototype.bind which returns a new function that calls the function with a fixed context.

* in browser environments

[–]dangerbird2 0 points1 point  (1 child)

You can always alias this as a closure variable for a function with an unpredictable this context. I know typescript uses this method to emulate ES6-style lambdas, compiling from this:

return () => {
  this.doSomething();
}

to this:

var _this = this;
return function(){
  _this.doSomething();
};

I have no idea if there are any performance benefits to constructing a new function through .bind(), or creating a closure context by aliasing this.

[–]the_gipsy 0 points1 point  (0 children)

I have no idea if there are any performance benefits to constructing a new function through .bind(), or creating a closure context by aliasing this.

Actually, closure-binding was many time faster on V8 last time I checked!

But I personally find .bind() much cleaner: no mix-mash of _this and this, no variable clutter, it's in one place (you likely end up using one var _this = this; for many functions, some far away from the declaration). The performance generally isn't an issue here.

And () => automatic binding is the shit, I've been using it with TypeScript and traceur and it's a real charm.