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

1

u/MadCervantes Feb 23 '18

Thanks! This is super helpful because it helps clarify to me why stuff seems kind of wonky in the way it's used. In particular 3. That's the way I've mostly seen it, but I didn't grok the new being that it added an empty object.

2 and 4 also seems to explain why React uses this the way it does. Basically when you bind something to this, and then call it without something to the left of the dot, instead of going global it goes the bound thing right?

1

u/delventhalz Feb 23 '18 edited Feb 23 '18

Correct. bind creates a new function with the the this parameter explicitly set.

const badGreeting = obj.hello;
badGreeting();  // Hello [object Window]

const goodGreeting = obj.hello.bind(obj);
goodGreeting();  // Hello [object Object]

By contrast, call and apply call the function immediately. We can use this to fix our bad greeting, or even call it with something totally different as this:

badGreeting.call(obj);  // Hello [object Object]
badGreeting.call('world!');  // Hello world!

That last example hopefully emphasizes that this is nothing special. It's just another parameter. It gets set in an unusual way, and has a downright nonsensical default value, but it's just a parameter.

1

u/MadCervantes Feb 23 '18

Cool, thank you!