this is a special keyword in JavaScript that refers to the object that is executing the current function.
In simple terms,
thisrefers to "who called the function."
1. Global Scope
var myVar = 100;
function WhoIsThis() {
var myVar = 200;
alert(myVar); // 200
alert(this.myVar); // 100
}
WhoIsThis(); // window.WhoIsThis()
In this case,
this refers to the global window object.2. In Strict Mode
"use strict";
function test() {
alert(this); // undefined
}
test();
3. Inside Nested Functions
var myVar = 100;
function outer() {
function inner() {
var myVar = 200;
alert(myVar); // 200
alert(this.myVar); // 100
}
inner();
}
outer();
4. Inside an Object Method
var obj = {
myVar: 300,
whoIsThis: function () {
var myVar = 200;
alert(myVar); // 200
alert(this.myVar); // 300
}
};
obj.whoIsThis();
5. Using Constructor Functions
function WhoIsThis() {
this.myVar = 200;
}
var obj1 = new WhoIsThis();
var obj2 = new WhoIsThis();
obj2.myVar = 300;
alert(obj1.myVar); // 200
alert(obj2.myVar); // 300
6. Using call() and apply()
var myVar = 100;
function WhoIsThis() { alert(this.myVar); }
var obj1 = { myVar: 200 }; var obj2 = { myVar: 300 };
WhoIsThis(); // 100 WhoIsThis.call(obj1); // 200 WhoIsThis.apply(obj2); // 3007. Using bind()
function SomeFunction(callback) { callback(); }
var obj = { myVar: 300, whoIsThis: function () { alert(this.myVar); } };
SomeFunction(obj.whoIsThis); // 100 (window) SomeFunction(obj.whoIsThis.bind(obj)); // 300 Precedence Order of this
bind()call()andapply()- Object method (dot notation)
- Global scope
Summary Table
| Context | this refers to |
|---|---|
| Global function | window (or undefined in strict mode) |
| Object method | The object itself |
| Constructor function | The new object |
call() / apply() | The object passed as argument |
bind() | The bound object |
| Arrow function | Lexical scope (outer this) |
Tip: Always ask yourself: “Who is calling this function?” That’s your this!
