DEV Community

Cover image for Understanding "This"
frk-ozbk
frk-ozbk

Posted on • Updated on

Understanding "This"

This keyword is a little bit tricky. In javascript, this keyword refers to an object that executing function.

By default, there is only Global Object. So if you declare a function that logs the This and invoke it, it will log the Global Object.

global.png

But things change when you declare an object and invoke the function from that object.

object-this5bc9f567b45e6383.md.png

Why did the function log the person object?

Because the object that executes or invokes the "consoleThis" function changed. Now the person object execute the function.So this keyword refers to person object.

So what are the benefits of this keyword?

Well, you can create reusable functions. What does that mean?
Let's look at the example.

reusable.md.png

We declared two objects: personA and personB
These objects have three keys: name, key and increaseAgeBy function.We invoke increaseAgeBy(1) on personA object.Inside the increaseAgeBy function this will refer to personA object.
personA.age was 22 so now personA's age is 22 + 1 = 23.
Then we invoke increaseAgeBy(10) on personB object.Now this will refer personB object.personB.age is 18 so now personB's age was 18 +10 = 28.

What if I do this?

LogIt.png

We declare the same person object. Then we declare the logIt variable outside the object then assign the logName function inside the personA object. But when we invoke it, we don't invoke logIt function from personA object, we invoke from the global object so this keyword will refer global object. There is no variable named "name" inside the global object so the function will log "undefined".

Apply, Bind and Call Function Methods

Call and Apply methods work similarly. Both invoke the function they called and their first parameter is that Object that you want to bind this. The difference is that Apply takes arguments as an array; Call requires the parameters to be listed explicitly.

apply.png

call.md.png

Bind works differently. It creates a new function when called, has its this keyword set to first parameter.

sayMyName.png

Why did not sayPersonAName function return 'Lucy' instead of 'Jack'?
Because we bound sayMyName function to PersonA object. This created a new function that has it's this keyword set to PersonA. So whenever we call this function its this will refer to PersonA object.

Thank you for reading. See my other posts below.

What is the difference between var and let

What is syntactic sugar

Top comments (0)