Quantcast
Channel: Andela
Viewing all articles
Browse latest Browse all 615

How and When to Use Call, Apply, Bind, and the (Mysterious) ‘this’ in JavaScript

$
0
0

Every Javascript programmer goes through the same confusing thought process. What is the difference between call, apply, and bind? And why is the this keyword used differently in JavaScript than other object-oriented languages? Help!

I wanted to put an end to all the confusion caused by the context 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 customize its context in a smart and performant way.

Functions, Properties, and Methods

JavaScript, unlike other languages (such as Ruby, for instance) allows for an object to contain functions as properties. These properties are commonly known as methods.

See example below:

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.

The differences between call, apply, and bind

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.

When and why should I use them?

  1. To borrow another object’s methods or
  2. To create a custom value of this

1. Borrowing another object’s methods

a) Call

Here’s how 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.

Meaning, it’s possible to invoke an object’s method on a totally different object.

From the above examples, thegetYearOfRelease method belongs to the theFirm object. However, we were able to call it on the theDaVinciCode object! How magical is that?

Another example would be a typical use 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 theobj 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.

b) Apply

To make it easy, let’s use the (call) examples above, but instead use apply :

Again, the only difference between call andapply is that with apply you have to pass arguments as an array. Not doing so will fail with a TypeError.

c) Bind

bind returns a function. For example:

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.

2. Creating a custom value of ‘this’

As seen in the above examples, it is possible to invoke an object’s method(s) on another. Let’s take a step back.

method can access and modify the properties of its parent object. This is where JavaScript wins big time! But how can an object reference its own properties and even modify those properties itself?

What is the ‘this’ keyword?

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:

An object is able to access and manipulate its own properties all thanks to the this keyword. In the theFirm object, thegetYearOfRelease method is able to access its parent’s yearOfRelease property.

There are many misconceptions around the value 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 called. 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 undefinedsince 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!

Problem solved! We assigned the value of this to the user object which in turn gives us access to the user's name property.

Questions or comments? Make sure to follow me on Medium to get more engineering advice.

Oded Coster, CTO at Intelligent Hack, recently shared his philosophy and best practices around simple programming. Find out how you can be avoiding unnecessary complexities in your code.

The post How and When to Use Call, Apply, Bind, and the (Mysterious) ‘this’ in JavaScript appeared first on Andela.


Viewing all articles
Browse latest Browse all 615

Trending Articles