When to Use JavaScript’s “this,” “call,” “apply,” and “bind”

Developers who use JavaScript all undergo a perplexing mental process. One common challenge is distinguishing between the distinct:

call , apply , and bind ? And why is the this keyword used differently in JavaScript than other object-oriented languages? Help!

My aim is to eliminate any confusion about the origin of

this keyword in JavaScript objects and functions. In this article, I’ll help you understand when to use this to access and modify object properties as well to use customise its context in a smart and performant way.

Functionalities, Properties, and Methods

Compared to Ruby and other languages, JavaScript allows the use of functions as properties of objects. These functions are commonly called ‘methods’ which are used in defining custom functions, creating objects, and specifying attributes. With these features, JavaScript has become a flexible and robust programming language that allows developers to create engaging and interactive web applications.

Kindly check the following example:

needsRefill is a property of the coffeeMaker object. And since it’s a function, it has to be invoked to determine whether the coffeeMaker needs a refill or not.

Differentiating call, apply, and bind methods

Both call and apply invoke a function. Their only difference is that call accepts arguments in a comma-separated fashion while apply requires arguments to be passed as an array or an array-like object.

Bind returns a function. Examples coming up.

Can you enlighten me on their significance and appropriate usage?

  1. The term “borrow” refers to the act of using the attributes or
  2. Creating a distinct rendition of the this keyword

1. Implementation of functions from another object

a) Call Method

Steps to Follow: call is defined in the MDN docs:

The call() allows for a function/method belonging to one object to be assigned and called for a different object.

In other words, it’s possible to employ a method of one object into another.

This can be observed in the getYearOfRelease method belongs to the theFirm object. However, we were able to call it on the theDaVinciCode object! How magical is that?

Another example of this is the frequent utilization of hasOwnProperty to check if an object possesses a particular property. It’s recommended to (play it safe) use Object.hasOwnProperty.call(yourObj, yourProp) instead of calling hasOwnProperty directly on the object (which overlooks the fact that the obj might not be a true instance of the Object . For instance, if the obj was created by calling Object.create(null) , then calling obj.hasOwnProperty(prop) will fail since the obj does not have reference to the Object.prototype . By using call , we are able to ‘borrow’ the hasOwnProperty method from the Object.

Apply Method (b)

To make things simpler, let’s revisit the (call) examples mentioned earlier, but apply :

Once again, the sole distinction between call and apply is that with apply you have to pass arguments as an array. Not doing so will fail with a TypeError .

Bind Method

In bind returns a function. For example:

In this boundFunction refers to getYearOfRelease and will be called on the theDaVinciCode object. You can call bind passing the arguments directly or pass the arguments in the bound function itself.

Creating Your Own “this” Value

As demonstrated previously, it’s possible to call a method on one object from within another. However, let’s take a step back.

An object’s method can access and manipulate the variables linked to that object, one of the strengths of JavaScript. As a result, objects can use and modify their own properties as needed.

Which Term Best Describes This Scenario?

The this keyword is the ultimate cause of confusion for programmers because it’s used differently in object-oriented coding languages. Here’s my attempt at officially clearing things up:

Because of this, an object can inspect and modify its own properties. this keyword. In the theFirm object, the getYearOfRelease method is able to access its parent’s yearOfRelease property.

Numerous individuals overvalue the significance of this in an object or in a function. Keep this in memory: the value of this is assigned when a method or function is invoked. And NOT where it is defined!

When theFirm.getYearOfRelease is being invoked, the value of this is assigned to the theFirm . However, calling getYearOfRelease without the dot will assign the value of this to the global / window object. See the example below:

Calling myFunc returns undefined since this is pointing to the window object which at that point doesn’t contain the yearOfRelease property. So again, to reiterate, the value of this is only assigned where a method or function is invoked but not where it is defined.

Calling sayHello returns ‘Hello, undefined’. How can the undefined be resolved? Thanks to call , apply or bind (that we discussed above), we can assign the value of this to whatever we want!

There goes that pesky issue! In simple terms, we computed the value of this to the user object which in turn gives us access to the user's name property.

Related Article: Essential Books for Software Developers to Master JavaScript in 2023

Join the Top 1% of Remote Developers and Designers

Works connects the top 1% of remote developers and designers with the leading brands and startups around the world. We focus on sophisticated, challenging tier-one projects which require highly skilled talent and problem solvers.
seasoned project manager reviewing remote software engineer's progress on software development project, hired from Works blog.join_marketplace.your_wayexperienced remote UI / UX designer working remotely at home while working on UI / UX & product design projects on Works blog.join_marketplace.freelance_jobs