Javascript this keyword
The this
keyword in JavaScript refers to the object that is currently executing or being referenced within a function or method. It provides a way to access and manipulate object properties and methods based on the context of the function invocation.
The value of this
is dynamically determined at runtime and depends on how a function is invoked.
Input:-
Output:-
Global context
In the global context, this
references the global object, which is the window object on the web browser or global object on Node.js.
This behavior is consistent whether the strict mode is applied or not.
If we assign a property to this object in the global context, JavaScript will add the property to the global object as shown in the below example:-
Input:-
Output:-
Call() and apply() method
The call()
and apply()
methods in JavaScript are used to invoke a function with a specified this
value and arguments. They are similar in functionality, but differ in how arguments are passed.
Input:-
Output:-
Bind() method
The bind()
method in JavaScript is used to create a new function with a specified this
value and any number of arguments pre-set (also known as partial application). It returns a new function that, when called, has its this
value set to the provided value, with a given sequence of arguments preceding any arguments passed when the new function is invoked.
Input:-
Output:-