The This Keyword in JavaScript
The This Keyword in JavaScript
2. Function Context:
- Regular Functions: In regular function calls, `this` refers to the global
object in non-strict mode, and `undefined` in strict mode.
function show() {
console.log(this === window); // true in a browser in non-strict mode
console.log(this); // undefined in strict mode
}
show();
const person = {
name: 'John',
greet: function() {
console.log('Hi, my name is ' + this.name);
}
};
person.greet(); // Hi, my name is John
function Person(name) {
this.name = name;
}
const person1 = new Person('John');
console.log(person1.name); // John
4. Arrow Functions: Arrow functions do not have their own `this` context, instead
they inherit `this` from the parent scope at the time of definition.
const person = {
name: 'John',
greet: () => {
console.log('Hi, my name is ' + this.name); // `this` inherited from parent
scope
}
};
person.greet(); // Hi, my name is if global name is not defined
5. Event Handlers: In the context of event handlers, `this` refers to the element
that received the event.
JavaScript provides methods to set the value of `this` explicitly for any function
call using `call()`, `apply()`, and `bind()` methods.
- `call()` and `apply()` invoke the function with a specified `this` value, and
additional arguments can be passed with `call()` as a list, and with `apply()` as
an array.
- `bind()` returns a new function, with `this` bound to a specific object, allowing
you to call it as a regular function.
function greet() {
console.log('Hi, my name is ' + this.name);
}
const person = { name: 'John' };
greet.call(person); // Hi, my name is John
greet.apply(person); // Hi, my name is John
Summary