JS Shorts — Bind

Prakhar Jaiswal
Nov 14, 2020

--

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.

Image by Pexels from Pixabay

— That’s all for today

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response