Middle
Tell about this in different contexts: in object methods, in arrow functions, and in regular functions.
sobes.tech AI
Answer from AI
In JavaScript, the value of this depends on the call context of the function:
- In object methods
thisrefers to the object to which the method belongs:
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
obj.greet(); // Alice
- In a regular function (not a method),
thisdepends on the mode and call method:- In strict mode (
'use strict') —thiswill beundefined. - In non-strict mode — the global object (
windowin browsers).
- In strict mode (
function foo() {
console.log(this);
}
foo(); // window or undefined in strict mode
- In an arrow function
thisis lexically inherited from the outer context, meaning it is taken from the scope where the function was declared, not called:
const obj = {
name: 'Bob',
arrowFunc: () => {
console.log(this.name);
},
regularFunc() {
const arrow = () => {
console.log(this.name);
};
arrow();
}
};
obj.arrowFunc(); // undefined or name from outer context
obj.regularFunc(); // Bob
Thus, arrow functions are convenient for preserving the this context from an outer function, while regular functions and methods have their own this value depending on how they are called.