Middle
Why can't the 'this' keyword be used in JavaScript?
sobes.tech AI
Answer from AI
this cannot be used in arrow functions to bind to its own context. Arrow functions do not create their own this, but inherit it from the scope in which they were defined.
Also, this is unreliable in callbacks of asynchronous operations or event handlers without explicit context binding (.bind(), .call(), .apply()), as its value can change or become the global object (in non-strict mode) or undefined (in strict mode).
Example:
function traditionalFunction() {
console.log(this); // this depends on the call
}
const arrowFunction = () => {
console.log(this); // this inherits from the outer scope
};
const obj = {
method: traditionalFunction
};
obj.method(); // this - obj
traditionalFunction(); // this - global object (window / global)
const obj2 = {
method: arrowFunction
};
obj2.method(); // this - inherited. If defined in the global scope, then global/window.