![]() |
VOOZH | about |
In JavaScript, this depends on how a function is called , it may refer to an object, global object, or be undefined (in strict mode), and its value is determined at runtime based on how the function is invoked.
The this keyword in JavaScript dynamically refers to the object that is executing the current function. Its value changes based on how and where it is used, not where it is written.
In an object method, the this keyword refers to the object itself, allowing the method to access, interact with, and modify the object’s properties and behavior within its scope.
In a JavaScript function, the behavior of the this keyword varies depending on how the function is invoked.
Syntax:
function exampleFunction() { console.log(this); // Refers to the current execution context}When used alone in JavaScript, outside of any specific context, the behavior of the this keyword depends on whether the code is running in strict mode or not.
When we call a function as a method of the object this keyword refers to the calling object.
Here this keyword is referring to the person object so it can access name and age values.
When we explicitly bind this keyword using the call(), bind(), or apply() method then this keyword default reference is changed to the object called using the above-specified methods.
When this keyword is used in global scope this is set to window object.
Arrow functions do not have their own this. Instead, they inherit this from the surrounding (lexical) scope, which means the value of this is determined by where the function is defined, not how it is called.
The precedence of the this keyword in JavaScript follows a clear order: bind() has the highest priority, followed by call() and apply(), then object method invocation, and finally the global scope.