JavaScript “this” keyword explained simply

Ninja JavaScript
3 min readJan 31, 2017

“this” in JavaScript is often mistakenly thought to refer to the current “scope” or simply to the enclosing object. Though the reality is more complicated, understanding the basics is actually very simple and can be broken down into just four simple scenarios. In this brief summary I will aim to give you the bulk of what you need to know.

What is “this”

when a function is called a new execution context is created by the JavaScript engine that exists until the function has finished executing. Every execution context contains a reference to an object, “this”.

What “this” refers to depends on where and how the function that is being executed is called. Identifying where the function is called (the “call-site”) will help you determine what “this” refers to.

the call-site is where the function is called

There are only four different scenarios to remember.

1. Default Binding

Default binding

When calling a function in a standard way shown above, “this” will actually refer to the Global object! In the browser the Global object means the Window object. In this example the console will log out a whole heap of stuff that exists on the Global object, including the variable “a” which has also been declared on the global object.

The result of console.log(this)

If none of the other rules below fit with your scenario, then default binding of this is probably the binding for “this” that is being used.

One exception to remember is if strict mode is enabled. By writing “use-strict” you can prevent anything from being declared on the global object.

2. Implicit Binding

If the function is contained within an object then that object will will be referenced by “this”. In the example below the object foo holds a reference to bar. foo will thus be logged out when bar writes “this” to the console.

Implicit binding
The console output showing foo as the “this” context of bar

3. Explicit Binding

bind, apply and call are all functions that can be used to explicitly set the value of “this”. The only difference between these functions is that apply and call can be used to pass parameters to the function, whereas bind is used purely to set the value of “this”.

In the example above we have set the “this” reference of bar explicitly in three different ways. Each time we have set “this” to be foo.

4. New Binding

When an instance of an object is created using the new keyword, “this” is always set to that same instance. Therefore, in this example, an instance of foo called bar has foo referenced by “this”

Conclusion

This is obviously a very quick tour of the “this” keyword but hopefully it can help to illustrate the key points.

Please comment or subscribe if you would like more JavaScript concepts explained in 500 words or less :)

--

--