DEV Community

The ‘this' keyword in Javascript

Rachel Ralston on February 02, 2017

The keyword this in Javascript can be a little slippery to wrap your had around at first. TL;DR When you refer to this in the global context, it ...
Collapse
 
madarauchiha profile image
Madara Uchiha • Edited

You didn't really touch the tricky parts of this. Like for example, what happens when you try to pass around a function that refers to this:

const o = {
  f: function() { console.log(this); }
};

o.f(); // prints o, no problems!

const g = o.f; // passed around the function instance, this could be passing to an event handler or some thing

g(); // prints window, oops. 

The main problem with this isn't that you need to pass it around in a parameter or that you might accidentally define things outside the scope.

The main problem with this is that this is determine when the function is called and how the function is called, in the example here, this changed because I no longer called f() with o behind the dot operator. So it defaults to the global object.

Collapse
 
guid75 profile image
Guid75 • Edited

And then, for a most advanced part, one could talk about arrow functions special rules and the bindfunction.

Collapse
 
wesleylhandy profile image
Wesley Handy

Helpful! I tutor students learning to code and will save 'this' 😉 post and use liberally. Well-done and fun to read!

Collapse
 
thegrumpyscot profile image
The Grumpy Scot

Excellent! Cheers :)

Collapse
 
necmettin profile image
Necmettin Begiter

This doesn't make any sense. The comments have hearts, but the content doesn't. (See what I did there?)

Collapse
 
nonsobiose profile image
Nonso Biose

Nice one Rachel. Just incase anyone is also curious about the "This" keyword in java,

why not check the link...... medium.com/java-for-absolute-dummi...

Collapse
 
eoinmurphy profile image
Eoin Murphy

Thanks! Your article actually cleared this topic right up for me.

Collapse
 
vouzamo profile image
John Askew

The most important thing to understand about this is that it refers to the caller from the call stack. Not to be confused with lexical scope.