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?

192 Upvotes

120 comments sorted by

View all comments

Show parent comment

1

u/js_developer Feb 23 '18

I think the school/classroom analogy has outlived it's purpose here.

"this" is context, the inner object that is built into every function. Passing references is done through this super function because while the child could access the higher scope, the child scope is isolated. It would have to return it's context (I.e. this) or assign it a different way. Both are valid depending on use.

Read up on constructors. This is an ideal way to use this as it's meant to be used. You can modify your constructor function (in ES6, class) by adding properties (like functions) to it's prototype object. You can then chain commands by always returning the context. Let me know if this last part is confusing.

1

u/MadCervantes Feb 27 '18

Still a little confusing. I've also come down with the flu recently so my brain isn't really running on all cylinders right now though.

What about this metaphor here? https://www.reddit.com/r/javascript/comments/7yki4d/_/dui3yab

Maybe any physical metaphor will be bad but playing with the different metaphors helps me grok stuff better.