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

4

u/AndrewGreenh Feb 19 '18 edited Feb 19 '18

His it was referring to the function using this.

One example:

function hello() {
  console.log(this.name);
}

What is this in the hello function? The only correct answer is "it depends on how it is called" .

let fred = {
  hello: hello, 
  name: 'fred' 
}
fred.hello() // prints 'fred', because the function was called on the Fred object. 

hello() // prints the global object or undefined because it is not called in any context 

And adding to your function constructor example: Your example will only work when called with the new operator. Calling a function with the new operator creates a new function that has its prototype set to the prototype of the function and the this of the function call we be bound to the newly allocated object. This new object will be returned from the call when the function does not return anything.