this keyword in javascript plays different role according to context. this is a javascript keyword, so it cannot be used as variable name.
- In object, this refers to the object who invoked or called that method.
- In function, this refers to global window object.
- On events, this refers to the Html element, which triggers that event. e.g. on button click etc.
- this returns undefined, when used in strict mode.
Only this keyword
this keyword without any object, function or events refers to global window object.
<script>
document.write(this);
</script>
outputs: [object Window]
this with class object
<script>
const car = {
company: "skoda",
make : 2024,
testfunction : function() {
return this;
},
myfunc : function() {
return this.company + " " + this.make;
}
};
document.write(car.testfunction());
document.write(car.myfunc());
</script>
outputs: [object Object] skoda 2024
Above example has two functions
testfunction() | Returns car class object. |
myfunc() | Returns class car company and make details. this is used to access current class object properties. |
this with function
<script>
var age = 40; // Global scope
function mytestfunction(){
var age = 50; // function scope
return this.age; // returns 40
}
document.write(mytestfunction());
</script>
outputs: 50
In above example, two variables with same name age is declared and assigned two different values. One variable is in global scope and another is in function scope. So, in function this refers to global window object, so, this refers to variable age of global scope and this.age outputs 50 and only age without this, inside function outputs 40.
this with events
<html>
<head>
</head>
<body>
<button onclick="this.style.color='red'">
Click Me...!
</button>
</body>
</html>
In above example, when user clicks on button, onclick event get triggered , and this in this.style.color refers to the html element button which has been clicked.
this keyword with strict mode
using this keyword in strict mode always return undefined.
<script>
"use strict";
document.write(this);
</script>
Outputs: undefined
this keyword with Arrow function
In Arrow function, this always refers to global window object like normal functions.
<script>
const test = () => this;
document.write(test())
</script>