r/javascript • • Feb 19 '18

help Explain like I'm 5 "this"

Okay, so I'm a designer learning to code. I've gotten pretty far learning presentationally focused code. So using JS to change the class of elements or to init frameworks I've downloaded from github is pretty easy. I can even do some basic If/then type stuff to conditionally run different configurations for a webpages CSS or JS loading etc.

But I'm taking a react.js class and.... I'm starting to get really confused with a lot of the new ES6 stuff it's going over. Like the way "this" is used? I thought this was just a way for a function to privately scope it's functions to itself? That's what I understood from jQuery at least, and uh... now I'm not so sure because it seems like the this keyword is getting passed between a bunch of different functions?

190 Upvotes

120 comments sorted by

View all comments

Show parent comment

6

u/elite_killerX Feb 19 '18

That's a very nice in-depth explanation, but definitely not ELI5. ELI5 would be:

All functions in JS are methods on objects, called liked this: myObject.myFunction(). this is the object before the . when you're in myFunction (in this case, it's myObject).

Special case 1: if you call a "naked" function (in the global context), this is simply the global object (because myGlobalFunction === window.myGlobalFunction)

Special case 2: If you don't like that rule, you can always bind a function, to explicitely set its this once and for all.

Special case 3: If you don't like that rule, you can apply or call a function, to explicitely set its this just this one time.