this in javascript.
Loading...
Definition: In JavaScript, the 'this' keyword refers to the context within which a function is executed. It is a special identifier that allows functions to access and manipulate properties and methods of the object it belongs to.
The value of 'this' is determined dynamically based on how a function is called. It can have different values depending on the invocation context:
const person = {
name: 'John',
greet: function () {
console.log(`Hello, my name is ${this.name}.`);
},
};
person.greet(); // Output: Hello, my name is John.
function sayHello() {
console.log(`Hello, ${this.name}!`);
}
window.name = 'Alice';
sayHello(); // Output: Hello, Alice!
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.name); // Output: John
function greet() {
console.log(`Hello, ${this.name}!`);
}
const person = { name: 'Alice' };
greet.call(person); // Output: Hello, Alice!
Understanding the context and value of 'this' is crucial for properly accessing and manipulating object properties and achieving the desired behavior in JavaScript applications.
For more in-depth information, you can refer to the MDN Web Docs on 'this'.
Happy coding!