Most developers still can’t get themselves around the use of
this. The reason is the dynamic nature of
this and the way it changes its context.
Today, we are going to see what actually
this is and why we need. Followed by related concepts of
Whenever you want to access the values in a function or context you use
this’ behaves differently in the different context:
1. Global Context
Anything which is defined in the global scope can be accessed by
this. By default, ‘
this’ always refers to the global object (so if you are writing code for a browser,
this will typically be the
2. Function Context
In a function,
this will default to the global object, which is
window in a browser.
It is worth noting here that if we tried
console.log(color), it would have returned
3. Object Context
this’ in an object points to the object always and works pretty much as you would expect it to:
The magic of objects is you can pass objects (and their methods — which is what you call a function when it is inside an object) as parameters to functions. So here we are passing in
call() changes the context of
this by passing the
obj object as the first parameter. If nothing is passed then
call() will point to the window’s scope.
apply() changes the context by passing the
obj object as the first parameter. If nothing is passed then the apply() will point to the window’s scope.
bind() also helps in changing the context of ‘
this’ but the difference is between
bind() is that
bind() only works once and it does not execute the function. It just binds the context with
The difference between
apply() is that
apply() expects the arguments as an array whereas
call() expect a single argument.
When you create an instance of a function, the context of
this moves to the newly created instance. In below example, the context of
this points to newly created instance
- In function and global scope ‘this’ always points to the window. Though this changes when you are in strict mode or Nodejs .
- In Object this points to the object’s context only
- In constructor, this points to the newly created instance.
- We can change the context of this by using — call(), apply() and bind()
- If you just bind the context and do not want to execute the function then use bind(). Always remember bind() works only once
- If you want to pass an array of arguments to this then you use apply(). Otherwise, use call().
- The beauty of this is its dynamic nature and it changes in the context you are running it.
We hope you found this useful! If so, leave some claps, follow JSIPE and share with all your friends, family and pets! 👫 👨👨👧👧 🐶