What is the purpose of the "this" keyword in JavaScript?
Asked on Jul 09, 2024
Answer
The "this" keyword in JavaScript refers to the context in which a function is executed, allowing access to properties and methods of the object it belongs to. It is dynamic and can change depending on how a function is called.
const person = {
name: "Alice",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet(); // Output: Hello, my name is Alice
Additional Comment:
✅ Answered with JavaScript best practices.- In the example, "this" refers to the "person" object, allowing access to its "name" property.
- The value of "this" is determined by the call-site, which is where the function is invoked.
- In a method, "this" refers to the object the method is called on.
- In global functions, "this" refers to the global object (window in browsers) unless in strict mode, where it is undefined.
Recommended Links:
← Back to All Questions