What is ‘this’ in javaScript?

Divya Mishra
3 min readDec 18, 2021

--

in short and crisp!… ‘this’ refers to the instance of current object.

I’m going to take you through that each How ‘this’?! which makes me to place console.log in every place to check the existence of this.

Photo by Brad Stallcup on Unsplash

=> First, let’s see what is ‘this’ in global environment,

If we have Normal Function call ‘this’ will be ? — Window object .

=> As Method Invocation Well, in method it refers to the lexical parent of object.

  • In Arrow function, ‘this’ refers to its lexical most parent, never creates its own execution context.
  • normal Function creates context with its parent object and set this to Obj .

Key points to remember in case of method invocation-

1. Always create method as normal function instead of arrow functions to avoid fuss.

2. What if in case of arrow functions, In place of ,

var title = “Outside Global title”;

will have,

let title = “Outside Global title”;

result would be same? let see,

No ? why ? It’s ‘undefined’, because this is looking for title in global object (var) but here we have (let) which is not comes in global but in Script section, if you got this, Kudos! else read scoping of let, const and var

3. ‘this’ in Event Handlers, refers to element.

=> In Indirect Invocation Here we explicitly specify an object that needs to be used as ‘this’, using call, apply and bind method.

Here, we pass target object as first argument, followed by more required arguments, separated by comma in case of call and as array in case of apply. If we want to invoke sometimes else in code then we use bind.

=> Constructor Invocation ‘new’ is the keyword used for constructor invocation.

Here, in below example Car is one constructor function with property name which we will set from external context of obj. Inherited to taxi object created from Car constructor function.

--

--

Divya Mishra

Frontend Developer. prefer reading, learning expression of writing.