Transform Your Code with the Magic of “this” in JavaScript

Sodiq Akanmu
6 min readFeb 4, 2023

--

Photo by Zachary Keimig on Unsplash

Introduction

Are you ready to go into the fun world of JavaScript and learn about the secret power of the “this” keyword? Prepare yourself for an amazing voyage through the interesting realm of “this,” where you’ll uncover the causes of its actions and realize the full power of your code. With engaging examples and crystal-clear explanations, this guide will take you on a thrilling ride through the various bindings of “this”. You’ll be equipped to handle any coding difficulty that comes your way by the time this journey is over, and you’ll have the self-assurance to build robust and scalable systems. So without further ado, fasten your code boots, and let’s journey across the uncharted territories of the “this” keyword!

The “this” keyword in JavaScript refers to the object that the current function is a method of. It is a dynamically scoped variable, meaning that its scope changes depending on the context of the function’s call during runtime. “this” is a key and frequently misunderstood concept in JavaScript since the meaning can vary substantially based on the context in which it is used.

Bindings of “this”

The “this” keyword has four main binding in JavaScript: default binding, implicit binding, explicit binding, and new binding. Understanding these bindings is essential to utilizing the “this” keyword in JavaScript effectively since they each specify how “this” should be used in a specific context.

1. Default Binding

When the term “this” is used outside of a function or in the global scope in JavaScript, it is bound by default. In this instance, “this” refers to the global object, which is either “window” in a browser or “global” in Node.js.

Here’s an example of the default binding in action:

As seen by the first console.log statement, the “this” keyword in the example above refers to the global object when it is used outside of any function. The second console.log sentence demonstrates that when it is used inside the logThis function, it also refers to the global object.

It’s vital to remember that in strict mode, the global object is undefined and not the value of “this” in the global scope. You can enable strict mode by adding “use strict” at the beginning of your code or inside a function as shown below.

2. Implicit Binding

The “this” keyword in this binding refers to the object that the function is a property of. “this” specifies the object when a function is used as a method of an object. The object of which the function is a property determines the value of “this.”

Take for instance,

The function “greet” is an attribute of the “person” object in the example above. We may access the “person” object’s name property by calling person.greet(), which sets the value of this within the greet method to the person object. Implicit binding can be seen in this situation. Implicit binding is illustrated by this.

Let’s look at another example:

In this example, the “instructor” object has the “sayName” function set as a property, and when instructor.say() is called, the “instructor” object is set as the value of “this” in the “sayName” function. This is another example of implicit binding.

3. Explicit Binding

No matter how or where a function is called in the code, you can explicitly set the value of “this” for a call using an explicit binding method.

Three methods of explicit binding exist in JavaScript: “call”, “apply”, and “bind”.

You can call a function using the “call” method, and you can also set the value of “this” for that function call. The value you want to set for “this” is the first argument to the call method, and the other arguments are sent to the function individually.

Take for example:

The “call” method is used in the example above to invoke the “sayName” function and the value of “this” is set to the instructor object.

Similar to “call” is the “apply” method except that it accepts an array of arguments rather than individual arguments.

Let’s look at an example:

In the example above, the “apply” method was used to invoke the sayName function and set the value of “this” to the “instructor” object. The arguments to the function are passed as an array.

The “bind” method creates a new function using the first argument passed to “bind” as the value of “this.” The argument given to “bind” is set as the value of “this” within the original function when the new function is later called.

Here is an example below:

In the above example, the “bind” method was used to create a new function “instructorSayName” using “this” set to the “instructor” object. When the function “instructorSayName” was later called, the value of “this” within the “sayName” function was set to the “instructor” object, just as if we had used “call” or “apply”.

4. New Binding

The process by which the “this” keyword is bound to a newly constructed object when a function is called with the “new” operator is referred to as “new” binding.

When a function is called with the “new” operator, a new object is created and the “this” keyword within the function is set to this newly created object. Additionally, the prototype of the newly created object is set to the prototype property of the function.

Take for example:

In the example above, a new object is created by using the “new” operator to call the “Person” function. The properties “name” and “greet” are added to the object, and the “this” keyword within the “Person” function is set to the newly generated object.

It is crucial to keep in mind that the newly created object is returned without the need for a “return” statement when a function is called using the “new” operator. If a “return” statement is used and it returns an object, that object will be returned instead of the newly created object. If a “return” statement is used and it returns a non-object value, the newly created object will be returned anyway.

Arrow Function and “this”

JavaScript’s arrow functions provide a shortcut for writing anonymous functions (functions without a name). The way they bind the “this” keyword sets them apart from conventional function expressions.

The value of “this” in conventional function expressions depends on how the function is invoked. As explained earlier, it can be explicitly set using the commands “call,” “apply,” or “bind,” or implicitly set depending on the object containing the function.

However, in arrow functions, the context in which the arrow function was generated, not how it is invoked, determines the value of “this.” This means that if an arrow function isn’t inside another function, the “this” keyword inside the arrow function will always refer to the “this” value of the outer function or the global object.

Simply put, arrow functions do not have their own “this” value; instead, they inherit the “this” value from the enclosing scope.

For example:

Here is another example of an arrow function that refers to the “this” keyword of the outer function:

In the example above, the “greet” function in this example was defined as an arrow function inside the “Person” function. The “this” value in the arrow function corresponded to the “this” value of the “Person” function, which was assigned to the newly generated object “elie,” when the “greet” function was invoked.

It bears mention that the use of “call,” “apply,” or “bind” cannot alter the “this” binding in arrow functions. Regardless of the method used to invoke the function, the “this” value within an arrow function remains the same. This makes arrow functions especially beneficial for callbacks and event handlers, where the value of “this” frequently changes unexpectedly.

Conclusion

In conclusion, learning JavaScript’s “this” keyword is a crucial step in becoming a true JavaScript expert. This essential yet frequently perplexing concept can make or break your code and is the key to utilizing the language’s full capability. You will be able to write code that is not only more efficient but also more elegant and dynamic if you have a thorough understanding of the default binding, implicit binding, explicit binding, and new binding, which are the four basic bindings of “this”. The ability to develop flexible, adaptive, and scalable code that can grow and evolve as your projects and requirements change will enable you to take on any challenge that comes your way. So, embrace the “this” keyword, master it, and become a true JavaScript ninja!

--

--

Sodiq Akanmu

Coding artisan and educator, dedicated to crafting elegant and innovative applications that merge form with function.