Junior
What is context in JavaScript
sobes.tech AI
Answer from AI
In JavaScript, the context (or 'this') is the value accessible inside a function through the keyword this. The context determines which object the current function call belongs to.
For example:
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
obj.greet(); // Will output 'Alice' because `this` points to `obj`
The context depends on how the function is called:
- In object methods,
thisrefers to the object itself. - In a regular function (non-strict mode),
thisrefers to the global object (window in browsers). - In arrow functions,
thisis inherited from the outer lexical environment.
Understanding the context is important for correctly working with methods and event handlers.