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, i... [Read Full]

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.

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

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

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

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

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...

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.

code of conduct - report abuse