JS Shorts — this

Prakhar Jaiswal
3 min readNov 15, 2020

|warning: this shorts might not be that short :D

this is one of the most confusing concepts of javascript, it behaves a little differently when compared to other languages. The value of this keyword depends on what context (global or object) the function is called.

There are a few rules that must be kept in mind while working with this keyword. The below examples explain the working of this in different scenarios.

  1. Global Context — In global context the value of this keyword refers to the global object ie the window object. Checkout the example below, the output shown here is true

2. Function Context — In case of functions, the value of this keyword depends on how the function is called. Usually in non-strict mode, if the value of this is not set while calling the function, it defaults to global scope. However, we can explicitly set the value for this using function call, bind or apply.

3. Class Context — The behaviour for classes is similar to functions since classes are functions under the hood. The major difference is that classes have their own this object and all the properties of a class are tied to it. All non-static methods within the class are added to the prototype of this.

Similar to functions, we can provide a new context using a new class but that applies only to the unbound methods, the bound methods remain unaffected. Notice below, how a bound method doesn’t get affected.

4. Arrow Function — Finally, if a function is an arrow function it ignores all the above rules and takes the this value from the place where it’s defined.

That was a lot to take and a lot of rules, but that’s how our beloved Javascript is. For an in-depth study refer MDN.

That’s all for today

--

--