In this article, I will talk about different nuances of this
keyword in Javascript.
this
If you access this
simply without any object reference, then it would simply mean that, you are referring to global window
object.
For eg:
Now executing function f()
f()
VM815:1 This object here is [object Window]
this
Now consider this example
As you can see, inside the obj's
scope, this
refers to obj
object itself, not the global window object.
this
outside the function of object’s scopeNow consider this example.
As you can see, inside the add()
’s scope, this
was pointing to obj.this
. However inside the inner function h()
( even though the scope is within obj
), this
has been reverted to global scope.
Take a copy of obj.this
as that
and reuse inside h()
. Complete example given below.
obj.add(20);
VM2045:1 This inside add is [object Object]
VM2045:1 That ( this) inside h is [object Object]
30
obj.add(20);
VM2045:1 This inside add is [object Object]
VM2045:1 That ( this) inside h is [object Object]
50
this
using apply()
& bind()
If instead of taking a copy of local this
and re-using it, you actually tell the inner function to get glued to the object itself using apply()
& bind()
.
obj.add(20);
VM2092:1 This inside add is [object Object]
VM2092:1 That ( this) inside h is [object Object]
30
obj.add(20);
VM2092:1 This inside add is [object Object]
VM2092:1 That ( this) inside h is [object Object]
50
this
using a constructorBy default, functions starting with capital letter will be treated like a constructor for that particular construct. In below example, I’m creating a new type called P
.
What I did? I simply created a constructor for P
and assigned the incoming num
to P.num
. This is achieved implicitly by using this
keyword. p
is filled from prototype P
.
p.num
10
Now, let me omit the new
keyword and call the constructor like a normal function, like this.
p1 = P(10);
p1.num
VM2340:1 Uncaught TypeError: Cannot read property 'num' of undefined(…)(anonymous
What just happened ?? There is no member named num
for p1
??? So what’s type of p
then???
typeof p
"object"
Aha.. p
is type of generic object, not our mighty P
. So what about the instruction this.num = num
would have done ?? You guessed it right. It just added num
property to global window
object. Or in other words, this
pointed to window
object.
window.num
10