The most confused keyword in JS: this.

Rhea RB
Oct 27, 2022

--

Javascipt is a single threaded and interpreted langugage.

This Keyword

this references the object that is referencing the current function.

In function it references global this.

Code snippet:

function run() {console.log(this)}
run();

Now, if the run the above code using node, we get the this pointing to global object.

In a browser, the this keyword refers to the global browser object.

If it is a method in object this references the object.

const a = {   title:"this is JS",   book() {     console.log(this)
}
}a.author = function() { console.log(this.title);}
a.book();
a.author();

The output would be,

Simple, right ?

This keyword is easy, but confused one.

Anyways, Thank you for reading !!

--

--

Rhea RB
Rhea RB

Written by Rhea RB

Hello ! I am a senior software engineer, passionate about tech and product.

No responses yet