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
1
u/phpdevster Feb 19 '18
Not OP, but IMO the fact that
thisrefers to the calling context rather than where it "lives" makes it a major foot gun.It's super easy to inadvertently assign a function that contains a reference to
thisto some other function, or call it from within a different context (such assetIntervalor something else) and then getundefinedfor whateverthiswas referring to.You have to explicitly do shit like
var myFunc = myObj.myFunc.bind(myObj)to ensure the function retains the context you want it to have.Very, very, very rarely have I ever needed to deliberately change the context of something by
binding a different object. I feel the default case should have been to makethisrefer to the context it was defined in, but still provide a way to override it withbind/call/applyin the rare cases you need to.I don't avoid
thisas much as I used to now that I know the rules concerning it's behavior, but I also prefer using simple closure to do what I need to instead:Closure not only provides actual privacy, it avoids
thiswonkiness altogether.The downside is that there is a bit of a performance cost to this approach since you're creating brand new
sayNamefunctions each with their own closures for every person you create. This eats more memory than defining a constructor / prototype function.