Understanding "this" in JavaScript

This post is continuation of the series of posts on Modular approach in JavaScript

this is the continuation of scope. In different scopes this refers to different objects in JavaScript that's why, sometimes, it becomes difficult for new developers to understand where the this is referring to.

this in JavaScript behaves differently as compare to other object oriented languages like C++ or Java. Lets look at how this behaves in JavaScript

In JavaScript, this can be context, caller or owner of the function. Below are the examples of all three scenarios.

As Context
- If the function is called in the global scope then this will refer to the window object

- Calling function by changing context

We can change context of any function using Function.call or Function.apply

As Caller
If any event triggers the function then this refers to the target of the event.

As Owner 
All object hold the ownership of function defined within those object.

Another example could be

I have tried to illustrate behavior of this with code examples. If you need further clarification then do post your comments. I will be more than happy to reply your specific queries.

Comments