What is “this” in JS #2

Badal Sharma
3 min readJun 27, 2021

--

Hi everyone, in part-1 we have seen what this is not, but we still have some questions about “this”. In this part, we will totally focus on how “this” works. In a previous blog, we used the term call-site, which is very important how “this” works.

call-site :

The location where the function is called, NOT where it is declared.

There are 4 rules to determine call-site.

Default Binding:

This rule is the default catch of all rules. Means, where none of the other rules apply, this rule applies. The global object is bind to the function, when default binding is applied (Standalone function invocation). See example,

When strict mode is there, a global object is not available for default binding. this = undefined

we got the error.

Implicit Binding:

When we are calling a function with context object, that will be used for “this” binding.

Implicit lost :

Sometimes implicit binding loses binding and falls back to the global or undefined(based on condition).

As we expected output is 2, because we thought the bar is just a reference of obj.buzz, but it’s not. It just assigns a reference of property buzz (just normal property assignment). and then call it standalone, so default binding is applied and output is “global”.

Explicit Binding :

You can force a function call to use a particular object as context(this binding) with call, bind, apply.

New Binding :

When a function is applied with the new keyword, then it’s called new binding. And following rules applied.

  1. A new Object is created(aka constructor).
  2. The newly constructed object is [[Prototype]] linked.
  3. The newly constructed object is set as this binding for that function call.
  4. Unless the function returns its owned alternate object, the newly invoked function-call will automatically return the newly constructed object.

Arrow Function (Exception) :

All the way we are talking about “this” is runtime binding, depends on call-site at run time. But in the arrow function “this” works differently. its mechanism is lexical “this” not dynamic. which means “this” derived from the parent.

if it was a normal function then the expected output would be 2, but it is an arrow function, “this” is derived from the parent. And in this case, the parent is the global scope. so the output is 3.

So In this blog, we have covered 4 rules(default, implicit, explicit, new binding) of call-site. and I hope now “this” makes more sense to you. And the exception mechanism of “this” (lexical “this”).
But it will be more interesting when we use a mixture of these bindings. which we will cover in the next blog. Small example :

We will discuss it in the next blog of this series. Make sure that you read the next blog 😊.

--

--

Badal Sharma
Badal Sharma

Written by Badal Sharma

I am Software Developer. You can join me for outing on weekends.

No responses yet