r/javascript • u/MadCervantes • 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?
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().thisis the object before the.when you're inmyFunction(in this case, it'smyObject).Special case 1: if you call a "naked" function (in the global context),
thisis simply the global object (becausemyGlobalFunction===window.myGlobalFunction)Special case 2: If you don't like that rule, you can always
binda function, to explicitely set itsthisonce and for all.Special case 3: If you don't like that rule, you can
applyorcalla function, to explicitely set itsthisjust this one time.