Understanding JavaScript 'this' and call(),apply(),bind()

Understanding JavaScript 'this' and call(),apply(),bind()

'this' is a special keyword in JavaScript that confuses the developers.

Let's break down the core concept behind 'this'.

'this' keyword in JavaScript represents the object it's currently associated with during the execution.

By default, this represents the global window object

console.log(this); //Prints the global window object

Function context

When this is used inside the function directly, it points to the window object. In strict mode, it returns undefined to prevent errors due to pollution of global scope.

this in the object method - Refers to the object to which it's associated

this in the constructor method - Refers to the new object created

As shown in this example, 'this' inside the constructor and object method getName() refers to the object instance of the class.

this in Arrow functions - It does not have this binding so it refers to the object in its lexical scope

this in event listeners - On using this inside an event listener method, it always refers to the element on which the event listener is placed.

Due to this behaviour, we might need to bind the object context with functions before its execution to ensure 'this' always points to the correct reference.

Using bind()

bind() method permanently binds the object to the function and returns the new function.

Here, the bindLogFullName() function is referencing the getFullName() function along with object binding on the John object. So, 'this' will always point to John object.

Using call() and apply()

call() and apply() methods also serve the purpose of binding object references to the caller function at that point in time.

Here, 'this' object is dynamically bound based on the object reference passed to call() and apply(). It also makes use of parameters passed to the function.

The only difference between call() and apply() is that call() accepts arguments as separate parameters, apply() accepts all arguments as a single parameter (array of arguments list)


References