The `this` Keyword
How `this` is determined in JavaScript: call-site, arrow functions, and binding.
Short explanation
this refers to the execution context's receiver. How it's set depends on how
the function is called: as a method, a simple function call, or with
call/apply/bind. Arrow functions inherit this lexically from the
surrounding scope.
Syntax example
const obj = {
value: 10,
get() {
return this.value;
},
};
obj.get(); // this -> obj
const fn = obj.get;
fn(); // this -> global or undefined (strict mode)
const bound = fn.bind(obj);
bound(); // this -> obj
How JS handles it internally
When calling a function, the runtime resolves the this binding according to
the call type. Arrow functions do not create their own this binding; they
reference the this of the outer lexical scope.
FAQ
Q: How can I avoid this confusion?
A: Use arrow functions for callbacks when lexical this is desired, or
explicitly bind functions with bind to control this.