this In JavaScript
Javascript this
keyword is the most widely used keyword and is still quite confusing for beginners. this
points to a particular object in JavaScript and what is that object mostly depends on how a function that includes this
is called.
The function's this
keyword behaves a little differently in JavaScript than in other languages. Understanding this
is very important to learn advanced concepts in JavaScript.
In this tutorial, you will understand this
keyword and its use in different cases in detail.
- What is this?
- this outside function (Global)
- this in function
- this in arrow function
- this in method
- this in event handler
- Refer this to desired object
Table Of Contents
What is this keyword in JavaScript?
Every javascript function has a reference to the object which is called the function, that reference is known as this
.
In JavaScript, the value of this
stores the current execution context of the program so when this
is used inside a function then the value of this
is determined by how a function is called, which is a runtime binding of this
.
Example
alert(this); // refer to global object -> Window
let user = {
firstName: "John",
lastName: "Smith",
age: 24,
intro: function () {
return (this.firstName + " " + this.lastName + " has age = " + this.age);
// here this refers to user object
}
}
console.log(user.intro());
Try It
this
keyword has different values depending on where it is used:
- Alone or outside a function,
this
refers to the global object. - In function,
this
depends on how the function is called however by default it refers to the global object. - In normal function in strict mode,
this
isundefined
. - In a method,
this
refers to an owner object. - In an event,
this
refers to an element that received the event.
this Outside function - Global context
this
used outside any function and object methods has a global scope and refers to the window object.
this
outside function refers to the global object even in strict mode.
Example
this.user = "John";
console.log(window.user); // refers to window
num = 20;
console.log(num);
console.log(this === window); // true
Try It
Also in strict mode, this
outside the function refers to Global object ([object Window]).
Example
"use strict";
user = "John";
console.log(window.user); // refers to window
num = 10;
console.log(num);
console.log(this === window); // true
Try It
this in JavaScript function
The value of this
inside a function depends on how the function is called.
this
in function by default refers to Global object ([object Window]) in non-strict mode.
Example
user = "John";
function foo(){
var user = "Herry";
console.log(user); // Herry
console.log(this.user); // John
// this in function refer Global object
}
foo();
Try It
this in JavaScript function - strict mode
In strict mode, this
in function is undefined
because in strict mode JavaScript does not allow default binding.
this in arrow function
An arrow function doesn't have their own this
. It takes the reference to this from outer normal function.
In global code, this
in arrow function refers to the global object.
Let's see an example to understand.
Example
name = "John"
let user = {
name: "Herry",
showName: () => console.log(this.name), // this from Window (global)
sayHi: function () {
let fxn = () => console.log(this.name); // this from outer normal function -> user
fxn();
}
};
user.showName()
user.sayHi();
Try It
The 'name' is a global and a local variable in the object. When arrow function uses this
in 'showName' function then it refers to outer scope (Global) which is 'John' and when the 'fxn' run then it take reference of this
from the outer normal function which is 'sayHi'.
this in a Method
this
in an object method refers to that object.
You can use this
within an object method to represent object and object entities.
Example
let user = {
firstName: "John",
lastName: "Smith",
age: 24,
intro: function(){
return this.firstName + " " + this.lastName + " has age = " + this.age;
}
}
console.log(user.intro());
// this in method refers to the object
Try It
this in Event Handler
this
in a function that is used as an event handler for an event refers to the element which receives the event.
It is recommended to use addEventListener()
method to set the event handler because some browser does not allow this convention.
Here in the example below, we set an event listener function using the addEventListener
method. When you use this
in the event handler function then it points to the element which receives the event.
Example
<button id="btn">Click Me!</button>
<script>
const button = document.getElementById("btn");
button.addEventListener("click", change);
function change() {
this.innerHTML = "Button Clicked!"
}
</script>
Try It
this in inline event handler
Also in the inline event handler, this
refers to the element which receives the event.
this in event handler attached using HTML attribute
You saw in the above example that when the event handler is added to the element using addEventHandler
method then this
represents the element itself however when you add event listener using HTML attribute then this
in the function does not represent the element but it represents the Global object.
See in the example below.
Example
<button onclick="ShowThis()">Show this!</button>
<script>
function ShowThis() {
console.log(this)
}
</script>
Try It
But, if you want to use this
which points to the element in this case then pass this
as an argument in the function and use it in the event handler.
Example
<button onclick="change(this)">Button</button>
<script>
function change(thisOfElement) {
thisOfElement.innerHTML = "Button clicked!"
}
</script>
Try It
Refer this to desired object
As you have seen as far that a function's this
refers to a global object but you can make to refer to a specific object for a certain call or for always.
You may be knowing about the call()
, apply()
and bind()
. Using these 3 method you can set the context of this
inside a function irrespective of whether that function is being called in the global scope or as an object's method.
Let's see in detail with an example.
Set this using call and apply method
The call
and apply
method executes the function immediately after setting this
of another object to the function.
To set the desired this
, pass the reference of this
as the 1st parameter in the call
and apply
method and pass functions parameter and next you can pass the arguments of the function.
The only difference between the call
and the apply
is that function's argument is passed individually in call
method but passed as an array in apply
method.
Example
name = "Peter";
age = 15;
let user1 = { name: "John", age: 25 }
let user2 = { name: "Herry", age: 30 }
function intro() {
console.log("My name is " + this.name + " age, " + this.age + " years")
}
intro(); // Global this
intro.call(user1); // this of user1
intro.call(user2); // this of user2
intro.apply(user1); // this of user1
intro.apply(user2); // this of user2
Try It
As you can see in the above example, when function 'info' is called normally then this
refers to a global object while when called using call
and apply
its this
refers to the passed object.
Binding this using bind() method
bind()
method bind this
of another object and returns a new function.
Unlike call
and apply
methods, bind
does not invoke immediately, you can call it later which makes it suitable to be used as callback functions.
Example
name = "Peter";
age = 15;
let user1 = { name: "John", age: 25 }
let user2 = { name: "Herry", age: 30 }
function intro() {
console.log("My name is " + this.name + " age, " + this.age + " years")
}
var user1Intro = intro.bind(user1); // bind this of user2
var user2Intro = intro.bind(user2); // bind this of user2
intro(); // Global this
user1Intro();
user2Intro();
// or directly execute
intro.bind(user1)();
Try It
As you can see in the above example, the bind method binds another object to 'intro' function and return a new function that you can store to some variable or invoke directly.
Conclusion
this in javascript is very confusing and have different meaning in different scenario and different use case. This article explains this keyword in detail with examples.