We had to use binding before es6 and the new arrow functions syntax.
Today, since we do have the arrow synntax, it feels like an anti-pattern.
At those days we use to do:
// doSomethinng exist only one time in your memory
function MyClass(props) {}
MyClass.prototype.doSomething = function(args) {};
// each time you creating a new instance you creating new function in the memory
// should not do that without a real use-case
function MyClass(props) {
this.doSomething = function (args) {};
}
Combining both approaches make it even weirder,
first, you have a prototype function,
then, you create a new function for each instance that runs the prototype function with the current this
as the context.
And you are basically don’t need to do that, the this
is already your context natively.
You will lose the this
context only when you will treat this function as a callback.
So in the old days:
MyClass.prototype.doSomething = function(args) { this.doSomethinngElse(); };
var instance = new MyClass();
// because i am not use `this.` i am loosing the this
function callCallback(callback) { callback() }
// so this will break
callCallback(instance.doSomething);
// This will work
callCallback(instance.doSomething.bind(instance));
// today can be much more elegant so we don't need to work hard and overthinnking about binding
// my rule never passes a callback anymore (unless it make sense), always use arrow syntax
callCallback(() => instance.doSomething());