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

2

u/phpdevster Feb 19 '18 edited Feb 19 '18

That’s not right. You can’t even call this, you reference it

Ok mate, you know what I meant. I'll be more verbose:

"It's the context the thing that references it was attached to when it was called."

Happy?

It’s captured/created and set when the function is defined.

This is simply not true. I don't know why you think it is, but it's not.

  var makeJoe = function () {

         return {
              name: 'Joe',
              sayName: function () {
                  console.log(this.name);
              }
          }
      }

   var joe = makeJoe();
   
   window.setTimeout(joe.sayName);  // undefined because `this` now refers to the global/window object.

As you can see, the calling context defines what this is.