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.