What is THIS ?
JavaScript the most popular programming language in the world. Almost every developer has been using JavaScript for various purposes from web app, mobile app, scripting to desktop app etc. JavaScript is so simple yet it can do almost everything. One of the most confusing topic ever in JavaScript is this. this keyword sound so simple but I found many developers confused while using it. Introduction The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run. It severely depends on the runtime binding i.e, how its being invoked rather. Its value depends upon the context it appears. Cases Global When this is used standalone i.e, directly on the code not inside any scope then usually it gives the global object (in non-strict mode) while its undefined in strict mode. Class If this is inside the class context then its value will be the class instance itself whether its on constructor or in any methods. class ThisCalss{ name = "ThisClass" constructor() { console.log(this.name) // "ThisClass" upon instace creation } printName() { console.log(this.name) // "ThisClass upon method invocation } } Arrow Function Arrow functions' this value depends on the enclosing lexical context's this. const printName = () => { console.log(this.name); }; Result : As the printName is directly under global lexical scope the console will print undefined. class ArrowExample { name = "ArrowExample"; printName() { setTimeout(() => { console.log(this.name); }, 100); } } const arrow = new ArrowExample(); arrow.printName(); Result: Here arrow function lexical scope is ArrowExample class so the output will be ArrowExample (value of name). Conventional Function In conventional functions (functions declared with the function keyword), this is determined by how the function is called, not where it's defined. The value of this depends on the calling context. function showThis() { console.log(this); } // Called directly showThis(); // window (in non-strict mode) or undefined (in strict mode) // As an object method const obj = { name: 'Object', show: showThis }; obj.show(); // {name: 'Object', show: ƒ} // Using new keyword new showThis(); // showThis {} Object Inside object's method the this value is object itself. const laptop = { brand: 'Apple', getBrand: function() { return this.brand; } } console.log(laptop.getBrand()) // 'Apple' Passing this context We can control the this context value with the help of bind, apply, call. The bind, call directly invokes methods/functions with the this context value. The only difference between them is the second parameters. apply accepts comma separated value while call accepts the array in second parameter. function getThis() { return this; } console.log(getThis.apply('this apply')) // 'this apply' console.log(getThis.call('this apply 2')) // 'this apply 2' While bind will only create new reference of the function/method it will not be invoked. This bind is very helpful iff we have to pass the function as parameter to any other function/methods. function getThis() { return this; } const newRef = getThis.bind('this bind'); console.log(getThis()); // undefined console.log(newRef()); // this bind Conclusion Understanding this in JavaScript requires careful attention to the context in which it's used. Here are the key points to remember: The value of this is determined by how a function is called (runtime binding) Class methods and object methods naturally bind this to their instance/object Arrow functions inherit this from their enclosing scope Conventional functions can have different this values based on their calling context bind, call, and apply provide ways to explicitly control this binding Being mindful of these rules will help you avoid common pitfalls and use this effectively in your JavaScript code.
![What is THIS ?](https://media2.dev.to/dynamic/image/width%3D1000,height%3D500,fit%3Dcover,gravity%3Dauto,format%3Dauto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0oiigstotoem0mlkx6h6.png)
JavaScript the most popular programming language in the world. Almost every developer has been using JavaScript for various purposes from web app, mobile app, scripting to desktop app etc. JavaScript is so simple yet it can do almost everything.
One of the most confusing topic ever in JavaScript is this. this keyword sound so simple but I found many developers confused while using it.
Introduction
The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run.
It severely depends on the runtime binding i.e, how its being invoked rather. Its value depends upon the context it appears.
Cases
- Global
When this is used standalone i.e, directly on the code not inside any scope then usually it gives the global object (in non-strict mode) while its undefined in strict mode.
- Class
If this is inside the class context then its value will be the class instance itself whether its on constructor or in any methods.
class ThisCalss{
name = "ThisClass"
constructor() {
console.log(this.name) // "ThisClass" upon instace creation
}
printName() {
console.log(this.name) // "ThisClass upon method invocation
}
}
- Arrow Function
Arrow functions' this value depends on the enclosing lexical context's this.
const printName = () => {
console.log(this.name);
};
Result : As the printName is directly under global lexical scope the console will print undefined.
class ArrowExample {
name = "ArrowExample";
printName() {
setTimeout(() => {
console.log(this.name);
}, 100);
}
}
const arrow = new ArrowExample();
arrow.printName();
Result: Here arrow function lexical scope is ArrowExample class so the output will be ArrowExample (value of name).
- Conventional Function
In conventional functions (functions declared with the function keyword), this is determined by how the function is called, not where it's defined. The value of this depends on the calling context.
function showThis() {
console.log(this);
}
// Called directly
showThis(); // window (in non-strict mode) or undefined (in strict mode)
// As an object method
const obj = {
name: 'Object',
show: showThis
};
obj.show(); // {name: 'Object', show: ƒ}
// Using new keyword
new showThis(); // showThis {}
- Object Inside object's method the this value is object itself.
const laptop = {
brand: 'Apple',
getBrand: function() {
return this.brand;
}
}
console.log(laptop.getBrand()) // 'Apple'
Passing this context
We can control the this context value with the help of bind, apply, call.
The bind, call directly invokes methods/functions with the this context value. The only difference between them is the second parameters. apply accepts comma separated value while call accepts the array in second parameter.
function getThis() {
return this;
}
console.log(getThis.apply('this apply')) // 'this apply'
console.log(getThis.call('this apply 2')) // 'this apply 2'
While bind will only create new reference of the function/method it will not be invoked. This bind is very helpful iff we have to pass the function as parameter to any other function/methods.
function getThis() {
return this;
}
const newRef = getThis.bind('this bind');
console.log(getThis()); // undefined
console.log(newRef()); // this bind
Conclusion
Understanding this in JavaScript requires careful attention to the context in which it's used. Here are the key points to remember:
- The value of this is determined by how a function is called (runtime binding)
- Class methods and object methods naturally bind this to their instance/object
- Arrow functions inherit this from their enclosing scope
- Conventional functions can have different this values based on their calling context
- bind, call, and apply provide ways to explicitly control this binding
Being mindful of these rules will help you avoid common pitfalls and use this effectively in your JavaScript code.