Explain JavaScript this Keyword
In JavaScript, the this keyword refers to the context in which a function is called. Its value depends on how and where the function is invoked. Here are some common scenarios that illustrate the behavior of this.
1. Global Context
In the global execution context (outside of any function), this refers to the global object (window in browsers, global in Node.js).
console.log(this); // In a browser, this will output: [object Window]
2. Inside a Function
When a function is called in the global context, this refers to the global object.
function showThis() {
console.log(this);
}
showThis(); // In a browser, this will output: [object Window]
3. Inside a Method
When a function is called as a method of an object, this refers to the object.
const obj = {
name: 'John',
showThis: function() {
console.log(this);
}
};
obj.showThis(); // Outputs: { name: 'John', showThis: [Function: showThis] }
4. Constructor Functions
In a constructor function, this refers to the newly created instance.
function Person(name) {
this.name = name;
}
const person1 = new Person('Alice');
console.log(person1.name); // Outputs: Alice
5. this in Arrow Functions
Arrow functions do not have their own this context. Instead, this is lexically inherited from the enclosing function scope at the time the arrow function is defined.
const obj = {
name: 'Alice',
showThis: function() {
const inner = () => {
console.log(this);
};
inner();
}
};
obj.showThis(); // Outputs: { name: 'Alice', showThis: [Function: showThis] }
6. Explicit Binding
You can explicitly set the value of this using call, apply, or bind.
call
function showThis() {
console.log(this);
}
const obj = { name: 'John' };
showThis.call(obj); // Outputs: { name: 'John' }
apply
function showThis() {
console.log(this);
}
const obj = { name: 'John' };
showThis.apply(obj); // Outputs: { name: 'John' }
bind
function showThis() {
console.log(this);
}
const obj = { name: 'John' };
const boundShowThis = showThis.bind(obj);
boundShowThis(); // Outputs: { name: 'John' }
Summary
The value of this in JavaScript is determined by how a function is called. Understanding the different contexts in which this can be used is crucial for mastering JavaScript function invocation and object-oriented programming.
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
