A look at “this” keyword in JavaScript

Define “this”

Simply put “this” is a JavaScript keyword that always refers to an object, the object can vary depending on how the object invokes a function. “This” will always reference an object and if it is called on a function held in the global scope, then that reference’s value will be the ‘window’ object.

Simple function that logs “this”. After invoking foo() “this” looks at the owner of the function and holds that object as a value in this case the global object.

If we were to call this function with the window object we would log similar results. So let’s look at some examples of how we can make use of “this” and how it can benefit us.

In a method invocation “this” will be set to the object that owns the method just like before, however if we create the object and place “this” inside of that object we can access the object similar to an attribute.

This is also know as implicit binding because we are not explicitly telling JavaScript what “this” is, instead the engine knows to grab the object that is invoking the method.

Moving along we have explicit binding which is when we do want to tell JavaScript what this before we invoke the method. To do this we can take advantage of some instance methods known as call(), apply() and bind().

Both call and apply are similar and take what this points to as its first argument and then passes additional arguments (call uses commas to separate each argument and apply uses an array of arguments)

Now bind is useful because it will create a new function that permanently give “this” the value within its initial invoking. We can set that new function to a value and call that value and receive the “this” that was used to create the newStudent in this case.

Using “this” like this can make creating new objects very simple and fast. “New” which is another JavaScript keyword will construct new objects, when a constructor function is invoked like this, “this” will point to that new object.

Note when we use constructors functions, the function name is capitalized.

In conclusion the use of “this” as well as the function methods call(), apply() and bind() can all be powerful tools to learn and use in any JavaScript project. They come with their own set of rules and understanding the functionality of them can greatly improve your JavaScript skills. The beauty of JavaScript is the many ways to approach problems and its best to embrace newer approaches and continue to find value in them.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store