Skip to content

Instantly share code, notes, and snippets.

@joelburget
Created January 16, 2016 15:45
Show Gist options
  • Save joelburget/7f55601ad93db3e39b97 to your computer and use it in GitHub Desktop.
Save joelburget/7f55601ad93db3e39b97 to your computer and use it in GitHub Desktop.
discussing this / self

Quick note about self / this:

Since the beginning, the this keyword in JS has been confusing. I recommend getting a good grasp of it, but I want to point out one specific case.

It's common to need access to this in a callback. JavaScript's scoping rules used to make it necessary to capture this explicitly:

var self = this;
callMeBack(function() {
  doStuff(self);
});

That was best practice until bind came along, giving you direct access to this in the callback's scope.

callMeBack(function() {
  doStuff(this);
}.bind(this));

But today we can do better, since ES 6 arrow functions match the semantics we expect -- not rebinding this.

callMeBack(() => {
  doStuff(this);
});

I haven't seen a case since arrow functions came out where it's necessary to capture this through self.

As a general rule, I like using function declarations for top level declarations and methods, since they can be named (function doStuff() {}) which is helpful when debugging. But I always use arrow functions for unnamed functions / callbacks.

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