DEV Community

Cover image for #10) Explain 'this' keyword❔
Mayank Yadav
Mayank Yadav

Posted on

#10) Explain 'this' keyword❔

🔰this in JavaScript refers to the object that the function it belongs to and it depends on the object that is invoking the function.

image

✔In the above example 1, the function is invoked in the global context, the function is a property of global object.
Hence, the output of the above example will be global object.
But this code is ran inside the browser, so the global object is the window object.

image

✔In above example 2, id function is the property of the object person.
So, the this keyword will refer to the object person and will return Mike as output.

image

✔In above example 3, the id function is declared inside the object person but at the time of invocation, id() is a property of person2, therefore the this keyword will refer to person2.
And it will return David as output.

image

✔In above example 4, this keyword refers to the object driver but the driver does not have the property color.
Hence, features function throws an error:-
`Uncaught TypeError: driver.features is not a function'


Latest comments (0)