What is “this” in JS #3

Badal Sharma
3 min readJun 27, 2021

--

In the previous blogs, we have seen different rules (default, implicit, explicit, and new binding) on how “this” works. But it will be more interesting to see, how “this” works, when these different rules apply together, means suppose if call-site has multiple eligible rules(binding)?

default binding < implicit binding < explicit binding

Surprised right? Well in lines 15 and 16 it's simple implicit binding. So when we are calling fizz with obj1 in line 15, “this” inside fizz is set to obj1, and output is 2, same with line 16.
But in lines 19 and 20, it is interesting that implicit and explicit binding applied together. But according to the precedence of binding rules, explicit binding applied. So in line 19 when we call fizz, “this” inside fizz is set to obj2, and output is 3.

implicit binding < new binding

In line 12 simple implicit binding is applied, so when fizz called with obj1, “this” inside fizz is set to obj1. And we are adding a new property to obj1 in function fizz. So in line 13 output is 2.

In line 16 mix of implicit and explicit binding applied together. But according to the precedence of binding rules, explicit binding applied. So in line 16 when we call fizz, “this” inside fizz is set to obj2, and we added a new property to obj2, and output of obj2.a Is 3.

In line 20 mix of implicit and new binding applied together. But according to precedence rules of binding rules, new binding applied. So if you remember the rules for new binding, a new object is created and assign “this” to that object, and finally, that object is returned. So in this case bar will have a reference of that returned object. and we added a new property to the bar object so the output in line 22 is 4.(and it will not affect obj1)

Explicit Binding (call, apply) is not allowed with new binding.

“this” inside arrow function :

As we know “this” in-side arrow function is derived from parent.(lexical “this”). see Example,

In line 16 explicit binding is applied and we are calling with context object obj2, so it should be print 2. But it is printing 1 why?
If we see that in line 15 we are calling fizz with obj1, so “this” for fizz is obj1. And after execution, it is returning an arrow function that is assigned to the bar.
Now we are applying explicit binding to the arrow function with obj2. But it doesn’t matter because “this” inside arrow function derived from parent, in this case, fizz is the parent of that arrow function. And context object is already set to that function is obj1. So the output is 1.

I hope this series of articles helps you to understand “this” in JS. Keep practicing.😊

What is “this” in JS #1
What is “this” in JS #2

--

--

Badal Sharma
Badal Sharma

Written by Badal Sharma

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

No responses yet