JS Shorts — Bind

The bind()
method creates a new function that, when called, has its this
keyword set to the provided value followed by the arguments of the function.
In simple words, if we want to provide a value for this
keyword to any function tied to an object or a class, we use bind()
. If these functions are called without binding them to a scope, they would be called in a global context, ie the window object.
Syntax:
let boundFunc = func.bind(thisArg[, arg1[, arg2[, ...argN]]])
Consider the below snippet,

The above code produces undefined
as an output. This is because setTimeout receives person.getName as a callback function. The callback is executed in a global scope after the timeout hence the value of this.name
is missing.
One way to fix this problem is to pass in a separate function as a callback and invoke person.getName()
inside it, so that the getName
function is called with person
as a scope.

The other way to fix this problem is to simply use bind with getName
and assign the person scope to it.

Both these approaches work because we are providing a scope to the getName
function. Both of these snippets produce John Doe
as an output.
This was function bind in its most basic form. We can also use this to invoke methods of one object with other simply by binding it.

— That’s all for today