DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Let's Get 'this' in JavaScript Once and for All

Let's Get 'this' in JavaScript Once and for All

'this' is an important part of JavaScript code. Read on to learn from an expert web developer who to work with this aspect of JS.

Ankita Masand user avatar by
Ankita Masand
·
Sep. 25, 18 · Tutorial
Like (5)
Save
Tweet
Share
6.76K Views

Join the DZone community and get the full member experience.

Join For Free

Your knowledge of JavaScript can be pretty well judged by your understanding of this. The fact that people find it difficult to comprehend is because of its use in multiple and varied scenarios.

Let's get them right once and for all.

If I were to talk about this in a literal sense, it simply means — this very thing in front of me. “This jacket is cool,” claimed my sister holding that jacket in her hand. I replied back saying, “No, this one’s better!” I was referring to the jacket near to me and she was referring to the one near her and hence the use of this in respective statements.

Value of this depends on:

  1. The Execution Context
  2. Invocation

Execution Context

Execution Context is the environment in which the code runs. For example, the local variables of a function would be accessible in that function only and not outside of it. This is called Functional Level Scoping or Local Execution Context. Variables declared in the global scope (outside of any function) would be accessible in all the underlying functions. This is called the Global Execution Context.

Let’s consider this example to understand the difference between the two of them:


The value of this in the Global Execution Context by default is the window object.

The value of this in any Local Context depends on the way the function is called.

I. Calling a function in a Global context would have its this value as window.

II. Calling a function that runs JavaScript statements in strict mode will have this as undefined.

III. Calling a function that is inside an object.

The function add is one of the properties on object, obj. When we call add with reference to obj as obj.add(), it gets called in the context of obj. Properties a and b have definite value in the context of obj, so that result of  obj.add() is defined.

The cacheAdd variable stores the reference of the add function. If we execute this function at a later stage, it will run in the context from where it is called. In our example, we’re calling  cacheAdd in the global context, so it will have a global object as the this reference. Since a and b are not defined in the global context, we’re getting the value of a+b as NaN.

To prove this point, lets define a and b in the global context.

obj.add() evaluates to 3 as the value of a and b defined in obj is 1 and 2, respectively. When we run add after caching it in a variable and then executing it in the global context, it evaluates to 7 as the value of a and b in the global context are 3 and 4, respectively. So, a function that uses this may give a different result depending on the context in which it is executed.

Let's try another interesting example:

In this case, the add function returns another function and the value of a+b is executed in this inner function. obj.add() will return a function that has one console statement. So, we have to execute this returned function in order to get the sum of a and b. But this returned function (returned on executing obj.add()) will run in the global context and hence the value of a+b evaluates to 7 (the value of a and b in the global context is 3 and 4, respectively).

Here, the add function prints the value of a and b after a timeout of 500ms. setTimeout runs in the global context.

Why does setTimeout run in the global context? (I’ll explain about it in detail in my next post.)

this takes the reference of the immediate object calling the function.

Here, parentObj has childObj as one of the properties and add function is defined on childObj. When we call add as parentObj.childObj.add(), the add function takesthis the reference of childObj and variables a and b are not accessible from the local context of childObj  Hence the value of a and  b is undefined.

Linking to the Prototype Chain

If we instantiate parentObj to create childObj, its properties would be accessible in the childObj context.

Using Object.create 

When the add function gets called in the context of childObj, it first tries to look for values of a, b, and c in the context of childObj and if any of these values is undefined, it looks up to its parent context, which in this case is parentObj.

Using the new Operator

In this case, also, properties of parent are available in the context of child. As we can see in the trailing console statement, the constructor of the child is defined as the Parent. So, it first checks for values in the context it is called and then look up to its prototype chain.

This Ain’t Rocket Science!

By default, the code runs in the global context, i.e. it has access to the variables defined in the context of the window object. In each of the above cases, we’re just restricting the context to the  obj object. All the operations related to this will be carried out in the exact same way as they would have if the context was window. Even with the global context, if any of the values are not defined, it looks up to the prototype chain.

As we can see, the toString function is defined in the __proto__ property of obj, which means it is defined on the prototype of Object (because obj is created by applying the new operator to Object). As toString is not defined in the context of obj, it looks up to its prototype chain.

Let’s solve an interesting issue here.

My sister stubbornly refuses to share the candy with me and to support her claim, she says, she is the owner of this candy.

This is her candy:

So, somehow I have to modify the this reference so that the function whosCandyIsThis is used. JavaScript is an unconventional language, you can always mend it the way you want.

Call, Apply, and Bind. Here I Go!

With these three beautiful functions, you can modify the value of the this reference. In the above example, candy.whosCandyIsThis.call(myCandy) modifies the this reference of the whosCandyIsThis function to myCandy.

What Is call All About?

call explicitly passes the this reference to a function. In this case, it tells the whosCandyisThis function to use this  as myCandy.

The first argument of call is the this reference and if we have to pass in any additional parameters, you can do something like this:  candy.whosCandyisThis.call(myCandy, true).

Let’s take one more example.

Here, we’re passing the this reference explicitly with the displayMenu function defined in the hotel object to display the menu accordingly (isn’t this cool?).

But what if I want to display the menu based on the user’s location. For that, we’ll pass an additional parameter, location, to the displayMenu function. Let’s modify the above code to fit in our requirements.

The first parameter of call is the this reference and then you can pass in any number of arguments that you want. The displayMenu function now shows the list of menu items as per the location parameter.

Apply operates in the same way as call, the only difference being the way in which we pass arguments. Apply takes in the first parameter as the this reference just like we did with  call but other parameters are to be passed as an array.

Another function that can modify the this reference is bind. Unlike call and apply, that return the result of the function, bind returns a function. And this returned function can then be called at any later stage. It will run in the context of an explicitly passed bounded argument.

hotel.displayMenu.bind(ccd) returns a function that has the this reference of ccd. When we run boundFunction, it runs in the context of ccd and hence prints Espresso for location A.

I was trying an experiment. If I bind an already bound function to some other reference, would that function run in the context of the later binding? If this is true, I can do this endlessly and keep changing this reference with all the power I have! But, this is not true. You can only bind a function once. In the above example, I’ve tried to bind the bounded function again with pizzaCentre but when I execute this function, it prints the previous result which means its reference still points to the first binding (ccd).

Well, again, JavaScript is an unconventional language. If there’s freedom to modify anything as you wish, there are guards who protect the integrity. One such masterpiece is our cute Arrow Function.

This is how it works. Plain and simple.

Why are we even talking about arrow functions in this article? What’s so special about them?

In an arrow function, the value of this is that of its enclosing lexical context Lexical Context is block level scoping. It does not change with call, apply or bind.

Arrow functions maintain the binding of this and of its enclosing lexical context.

Crap! This arrow took away my candy.

As you can see, whosCandyIsThis is defined as an arrow function. So it will maintain the binding of its Lexical Context. On instantiating Candy, niks sets the owner and flavor for her candy. Tje whosCandyIsThis function gets bound to the niks reference.

So, when I try to call it explicitly by passing the this reference using call, apply or bind, it doesn’t work. The bindings of the niks.whosCandyIsThis function cannot be changed, whatsoever!

You might like my previous articles on Service Workers:

  • Service Worker Fundamentals

  • Building a Pokemon App to evaluate the power of Berries and Service Workers

JavaScript Object (computer science)

Published at DZone with permission of Ankita Masand. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java REST API Frameworks
  • Custom Validators in Quarkus
  • HTTP vs Messaging for Microservices Communications
  • Tracking Software Architecture Decisions

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: