Javascript ‘this’ Keyword

Mandeep Kaur
3 min readOct 29, 2018
© Mandeep Kaur

We recently covered a topic on javascript ‘this’ keyword in our coding bootcamp class session at Georgia Tech. This article aims to provide a quick refresher and reference to quickly grasp the different possibilities.

‘this’ Keyword

The JavaScript ‘this’ keyword refers to the object it belongs to. The value of ‘this’ differs depending on how a function is invoked, so we can’t know the value of ‘this’ just by looking at the function itself, but we need to know the context in which the function is invoked.

There are four rules for ‘this’, in order of precedence that can be used to determine what ‘this’ gets bound to.

Rule 1. Default Binding

When we invoke a function declaration or a function expression the ‘this’ keyword will be bound to the global object.

Default Binding

Rule 2. Implicit Binding

When we invoke a method the ‘this’ value will be bound to that object; a method is a function that is a property of an object.

Implicit Binding

Rule 3. Explicit Binding

We can explicitly set what the ‘this’ keyword will be bound to using one of these options: ´.call()´, ´.apply()´, ´.bind()´.

Explicit Binding

Rule 4. New Binding

When a function invocation is proceeded by the new keyword ‘this’ will be bound to the newly created object.

New Binding

Bonus Rule: Arrow Functions

With arrow functions, ‘this’ keeps the same value as its parent scope.

Arrow functions have two main benefits.

1. They have shorter syntax.

Arrow Function

2. ‘this’ in arrow function will always take its value from the outside.

Arrow Function

Conclusion

The value of ‘this’ is usually determined by a functions execution context. In the global scope, ‘this’ refers to the global object. The object that is standing before the dot is what the ‘this’ keyword will be bound to. We can set the value of ‘this’ explicitly with call(), bind(), and apply(). When the new keyword is used (constructor), ‘this’ is bound to the new object being created. Arrow Functions don’t bind ‘this’ — instead, ‘this’ is bound lexically.

Thank you for reading.

--

--