Understanding ‘this’ in Javascript

This in Javascript refers to the object to which the function belongs. The value of this is determined by how a function is called.’This’ refers to the “owner” of the function.In the case of a normal function like below ‘this‘ refers to the global object (window object)

this javascript

In the above example, a function WrapAll() is being called from the global scope. The global scope means in the context of window object

this and ‘use strict’

Here this is undefined as use strict prevent global object


Now we can see how the this keyword works in an objects point of view by creating a new object.To create an object,we need a constructor function

Callback functions

In the above object we use fetch which returns a promise.To the promise .then we give a call back function  as seen below

Here , we can see that the console.log inside the callback function gives the window object.This is because the callback function is a normal function in Javascript which is put in to the callstack by the event loop from the event queue.


To get the ‘this’ inside the callback we can use bind()

We can also use arrow function or fat arrow function for the scope value to be available inside.

While using angular5,we might come across situations where we have to use subscribe.On subscribe .then use callback function with fat arrow function for ‘this’ to be available inside.See more on fat arrow functions here https://truetocode.com/fat-arrow-functions-or-arrow-functions-in-javascript/854/

For documentation on this see this link


No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *