Skip to content

Instantly share code, notes, and snippets.

@fghhfg
Forked from jashmenn/self-eq-this-vs-bind.md
Created November 12, 2017 14:38
Show Gist options
  • Save fghhfg/7e1fdcf60420dd0d15413e74005cb0e0 to your computer and use it in GitHub Desktop.
Save fghhfg/7e1fdcf60420dd0d15413e74005cb0e0 to your computer and use it in GitHub Desktop.
Javascript var self = this; vs. .bind

The Problem

In Javascript this is bound in unexpected ways. Functions, in particular, create a new 'this' and so when you want to keep a reference to an "outer" object you sometimes see the pattern:

var self = this;

as in:

var self = this;
return function(whatever) {
  return self.foo(whatever); // `this` here is for the inner function
}

Is this a good pattern? Shouldn't we just use .bind(this) on the inner function?

Sources Say:

I've done some reasearch and here are a few links that discuss this idea along with a little summary of what they suggest.

Summary

To me, it seems that .bind definitely has it's place. For instance when you have a function in a variable and you want to attach it to a particular this.

That said, in the case of nested anonymous functions I think that using var self = this; is straightforward and requires less mental accounting vs. using .bind. For example, say we have two nested functions:

function foo() {
  return (function() {
    doSomething((function() {
      return this.name; // what is `this` again?
    }).bind(this));
  }).bind(this);
}

vs.

function foo() {
  var self = this;
  return (function() {
    doSomething((function() {
      return self.name; // `self` is easy to know because its defined 
    })
  })
}

Of course, because this is a matter of style the issue of "mental accounting" will differ from person to person. But to me, given the semtanics of Javascript's this, I think that self = this is easy to comprehend when you have nested callbacks.

See Also

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment