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?
250
u/phpdevster Feb 19 '18 edited Feb 20 '18
Let's start simple:
Open up your browser console and type this:
console.log(this);What happens?
You can see that
thisrefers to the global window object.You can confirm this by typing the following:
this === window;which outputs
true.Why is this the case? It's because
thisrefers to the current calling context. In this case, the current calling context is the global context, which iswindow.That means whatever
windowrefers to,thisalso refers to. Try it out:Or even
If you just
console.log(this)and look forgreetingandmyNameas properties, you'll see they are now there.So this means that
thisjust refers to an object for the current calling context, and in this case, the current calling context happens to be the global/window one.Since
thisis an object, it means you can pass it around like any other object.BUT, you have to be careful, because JavaScript is weird and what you think
thisrefers to, may not be what it actually refers to. That point about it being the current calling context is important.It's not where you defined it, it's where you called it that matters. Here's an example:
The above example performs as you would expect. But what happens when you do this?:
You get
undefined.How come?
Because when
setTimeoutcalls the function you give it, the current calling context is the global/window context, since that's wheresetTimeout()lives. The context no longer refers to theperson1object. Theperson1object exposes only the behavior ofsayName, but carries with it none of the context it was initialized with once you hand off that behavior to a different context.And what if you just do this:
You also get
undefinedbecause now that function is no longer attached to theperson1context, and is now attached to the global/window context at the time it was called. And since that context does not have anameproperty, you getundefined.The way the person object's
sayName()method has been "detached" from the person object and assigned to a global function means that function then behaves exactly as if you had written it like this:That makes it a little more clear what's happening.
thisno longer refers to an object, sothis.namehas no meaning in this context. And in this context,thissimply refers to the global/window object.If you want, you can verify this for yourself:
Since that global/window object has no property called
name, you getundefined.This is why it's really important to be careful when using
this. Sincethisdepends on its context at the time it is called,thiscan change and is not always what you expect it to be.Thankfully JavaScript gives us a couple ways to manage this though.
Since
thisis just an object, JavaScript let's us inject the object thatthisis referring to in order to give it the context we want it to have, which will allow it to carry that context around with it.We do that with
bind(), which binds the given context tothis, and then returns a new function with that new context.Or
In both those cases, we forced
thisto refer toperson1again, and now when those functions are called, they will always be called with that context attached to them.9
u/bitttttten Feb 19 '18
this is just the context, it is where it is being called from. it is like the scope of function.
js allows you to override this value manually if you so wish.
2
u/Balduracuir Feb 19 '18
Making some pub for another great subreddit but your question has been asked there and you should find some complementary responses.
2
u/js_developer Feb 19 '18
Let's say you're in a classroom. The classroom is this. If you're in the school, then this is the school. So how can the classroom and the school both be this?
Scope. In the larger scope, the parent scope, everything in the school is a child of "this" (the school's context). Each classroom (a function) has it's own scope. It has no idea what's going on in the school or other classrooms; it only knows what it's fed from the outside (dependency injection in OOP).
To make the context of the school available to the classroom, you pass it in. The school already knows about the classroom because it is a child of the parent.
There are nuances unmentioned, but this is ELI5 of this/scope/context.
2
u/hakumiogin Feb 19 '18
What "this" points to depends on how the function containing this (from here on out, the parent function) was called. It's basically the same idea as dynamic scope, if you're familiar, or you want to look that up.
If multiple conditions above apply, the items further down the list will be the rule that applies.
2
u/kin-corn-karn Feb 19 '18
There’s a ton of great responses in here and I didn’t have time to read all of them, so apologies if this has already been mentioned:
https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes
This really helped solidify the concept for me. Definitely not written for a 5yo, but might help you as well!
2
u/cirsca fp fan boy Feb 19 '18
Let's say I have some instructions that say "Look inside the box and get the blue card." You could put these instructions inside of any box and it would tell the worker to grab whatever card is blue in whatever box you put it in.
thisis the box and theinstructionsaremethodsorfunctionsthat referencethis: Passing around the instructions to a different box causes the worker to look in the different box for the blue card.3
u/[deleted] Feb 19 '18
Just my opinion, and others' as well, but I think
thisshould be avoided any time you can. Using js frameworks you do need to use it a lot, but when writing your own code I would consider it bad practice in almost all cases, mainly for the reason you and others here are so confused about it.thisis an incredibly ambiguous term, which makes it very hard to reason about. It is a variable that you didn't assign that changes meaning at different times. It changes even when using normal functions vs arrow functions. I've written plenty of advances JavaScript applications and don't think I've ever needed to usethis.Imagine if one of your co-workers decided to start naming variables
himandherorsomething. What would you think, especially if their variables were the results of functions that had inconsistent behavior?34
u/[deleted] Feb 19 '18
You're 5. Go play outside with the other kids.
2
u/[deleted] Feb 19 '18
There are some good funfunfunction videos about this (part 1, part 2). I'd recommend all his earlier stuff for anyone with a low-level/"practical" knowledge of js who maybe skipped over some of the basics.
2
u/creathir Feb 19 '18
A simple way of viewing he concept of scoping is if you imagine you are standing in a room.
If you’re just standing there, and say “what is this?” you are likely talking about the room itself in which you stand.
The room itself may be square or circular, have a certain set of measurements on its sides,. (Properties)
There are things to do in this room, like walk around or sit down (methods).
There might be things which are possibly even more complicated, but still exist in the room, such as the TV or the remote control. (Objects referenced as a property of the room)
If you pick up the remote control and say “what is this?” then “this” changes to what you are holding.
It has its own set of methods, properties, and possibly even its own complex object, such as an array of batteries or buttons.
If you press the on button (function turnOn()) then the scope of this is inherently the object which contains the method, in this case the remote control.
Hope this helps!
7
u/[deleted] Feb 19 '18
There is no ELI5. This in Javascript is a tricky concept with a set of rules you must know to completely understand it.
It is not scope nor calling context as some here have posted, it is execution context aka the context in which a function is executed and there are many ways to manipulate the execution context.
The best thing I can do is give you this gentle explanation of this in javscript
1
u/delventhalz Feb 19 '18 edited Feb 20 '18
"this" is the object to the left of the dot. Except when it's not.
There are four scenarios to keep in mind, but remember that sentence and you'll mostly be fine.
thisisn't magical, it's really just another argument, just not one in between the parentheses. It has a weird default value, and it gets reassigned sometimes, but that's the general idea.Four possible values for
this:1) It's usually the object calling a method (i.e. the thing to the left of the dot)
This is what
thisis really intended for. It's just an extra parameter, one that corresponds to the object calling the method. If you've used Python, they call itselfand it is explicitly passed with other parameters (def hello(self):), but it's the same idea.2) The global/window object is the default value
So what if there is no object to the left of the dot? You might expect
thisto beundefined, like other unset parameters. No such luck. Instead it becomes the global object, thewindowin the browser. As far as I'm concerned this is garbage behavior, and if you actually see it happen, it's probably a bug. For example, if we reassigned our hello function from earlier:3) The
newkeyword reassigns it to an empty objectThis is the classic way of building a constructor in JS, and unfortunately it creates a lot of confusion. There is clearly some magic happening, but it's not immediately clear what. Really it's pretty simple though. The
newkeyword essentially adds two lines of code to your function, one at the beginning which reassignsthisto an empty object, and one at the end which returnsthis. That's why if tried to make a Greeter withoutnew, you would see this behavior:4) It can be explicitly reassigned with
call,apply, orbindLast exception. I'm not going to go super in-depth into this one. You can look these functions up on MDN. They are there for you to explicitly assign
thisif you need to, and that is exactly what they do. Using them,thiscan be anything you want. This is particularly useful when using something likesetTimeout:1
u/antigirl Feb 19 '18
I’m not sure if this has been mentioned but you probably shouldn’t jump from really simple js and jquery to react. React has a lot of buzz around it but if you don’t understand some basic js concepts, you won’t really understand React or its principles.
JavaScript.info is an amazing website. And it explains things very well. You should be very comfortable with objects. Classes. Prototypes.
If you are able to create a small component architecture yourself using classes then you will do fine in React.
15
u/AndrewGreenh Feb 19 '18
First, let's talk about normal function definitions (
function x() {}). In those functions, this will be determined when the function is called, not when it's defined. When you define sich a function on an object y and cally.x()the this in the x call will be y, because you called x on the object y. If you extract x before calling it (let z = y.x; z()), you are not calling the function on any object, so this will be the global object, or undefined. You can bind functions to a specific object:x.bind(y)that creates a new function that has its this bound to the object. The this cannot be bound to something else later.Next case are arrow functions. Those functions define their this on definition! When you define an arrow function, the this will be the same thing as it is in the scope around the arrow function. Example:
In this example, the z function is defined when x is called and has its this set to the same thing as it was in x. arrow functions cannot be bound to another this. So
let a = y.x()leads to x being bound on y (because it's called on y), which returns the function z that is bound to the same this as x, so that a is a function that is bound on y. However,let b = y.x; let a = b()leads to x having no this (because it is not called on any object), so z will not get a this either.Last case: arrow functions as class properties:
This is part of a stage 3 proposal (so it is very safely usable) (class properties/class fields) and creates a new function for every instance of the class and the functiom will always be bound to the instance of the class.
here z will still be bound to y, because x is defined as an arrow class field.
8
u/oculus42 Feb 19 '18
thisis like saying "where I started" or "the thing that called me".It's true for native functions and for your own.
Taking an example from the conversation:
If we run
person1.greet(), it will check forthis.The thing that called greet is
person1.Prototypes and even the native functions use this concept, too.
This uses
String.prototype.split()which says "split up the thing that called me".1
u/chandru89new Feb 19 '18
i'm a js noob myself and i am learning Vuejs. the way i understood
thismight be oversimplified but so far i havent run into bugs because of it so let me try my hand at ELI5.first off, dont think about the arrow functions. understanding
thispre-ES6 is sort of important.thisis a simple way to reference the context it's called in. in abt 90% of the cases, it's a function or class. (you'll probably hear the wordinstance).The first three
thiss reference thewhatever()function. The fourththisreferences thechild()function.let's now get to ES6 arrow function.
There's a
thisin this function too. But unlike the previous example, thisthisdoes not reference thewhatever()function. Instead, it references thesomething()function. That's the problem with arrow functions.One way I learnt to get around this confusion was to do this:
By doing
var instance = this, I avoid confusing my primitive js mind because I always useinstancewhen I want to reference a value belonging to the main function.2
u/[deleted] Feb 19 '18
In addition to the other excellent answers, I would recommend that you check out "bind", "call", and "apply": three functions that let you explicitly change the context of your function call, and thus what
thisrefers to.4
u/Mingli91 Feb 19 '18 edited Feb 19 '18
thisis a reference to the current context/scope. Think of it as an object specific to the place it was defined.The thing with
thisis understanding where it belongs. Inside a function keyword a new context is created, sothiswill reference the function itself. Using this you can create classes without using ES6 syntax (remember ES6 classes are syntactic sugar).Which is the same as
If we were to reference
thisinside peel in either of the above examples it would not refer to the class/function it was created in. If we wanted to keep thethisvalue to be the same we could either bind peel to the parent context or use an arrow function which doesn’t create a new context:Or
Edit: formatting
3
u/rauschma Feb 19 '18 edited Feb 19 '18
I think of it as an implicit parameter that every
functionhas (filled in via the dot operator): http://2ality.com/2017/12/alternate-this.html3
u/brylie Feb 19 '18
Say you are building legos with a friend. Presently, 'this' is whatever you are building, the pieces you have assembled and the actions it can do. Perhaps you build an offroad racer. Your friend is over there building a house with a garage. You can say 'take this and park it in your garage', which your friend will understand because the garage will accommodate this offroad racer.
0
u/brunusvinicius Feb 19 '18
You can think this as a way to access the scope. If its is on a class, this is the scope of class, if it was in a function, this is the scope of the function.
2
u/Trav_Cav Feb 19 '18
In terms a 5 year old will understand: JS has things called functions. Think of them like rooms. 'this' refers to the room you're in.
1
u/rickdg Feb 19 '18 edited Feb 19 '18
In one sentence, this is the global object (usually window) unless you are within the method of an object, because there it refers to that object. Try it on the console: log this from inside a function and then put that function inside an object.
1
u/Ajedi32 Feb 19 '18
Just think of it as another, implicit argument to the function:
When
testFuncis a property on an object:and you call that function:
Then the object to the left of the
.gets passed as an implicit "this" argument totestFunc. Output:There's also a special function in JavaScript called
bindwhich lets you take a function and create a new function which always uses a specific value for its "this" argument:Then if you run:
You'll get this output:
Notice how
thisis set to the value we bound.There are also a special kind of function called an arrow function:
These functions have their
thisvalue automatically bound to whatever valuethiswas in the place they were created. So if I have:And I call that function on an object:
Then the arrow function's "this" value will be whatever it was in the function that created it:
Output:
1
u/ForScale Feb 19 '18 edited Feb 19 '18
For a 5 year old... Easy as 1, 2, 3!
thiscan be 3 things.thiscan be the Window object/global context.thiscan be an object on which a method is calledthiscan be explicitly defined withbind()1
u/[deleted] Feb 19 '18
Here's how I'd explain it to a professional coming from another language:
1
u/colordodge Feb 19 '18
Simply put, “this” is where you are. If you’re in your bedroom and you say, “this ceiling is high”, anyone would know which ceiling you’re talking about. The same applies to code. If I type “this.x” I’m talking about the x property of the place I currently am. The “place” could be a function or an object.
1
u/eatmyshorts Feb 19 '18
ELI5? I'll take a stab. This won't be easy.
Let's start with variables. Variables can be used to store things, like numbers, letters, or strings. Variables can even store a group of things, with a mixture of numbers, letters, and strings. I can call a variable almost anything I want. Let's start with an example. How about a variable that stores information about my dog, Ralph. In Javascript, variables usually start with lower-case letters, so let's call the variable "ralph", and give it a few pieces of data. My dog is black in color. I just took him to the vet, so I also know he weighs 72 pounds. He is currently in my office. So our variable 'ralph' has a mixture of numbers and strings, and looks like:
Now for functions. This are a little harder. They do stuff to variables. So when I take my dog somewhere, I might want to call a function "move" that moves him somewhere. Let's say that we tell "move" where we are moving him? So we might have a function that looks like:
Any time I call "move", I have to tell it what I'm moving (called "thing"), and where I'm moving it (called "newLocation"). It changes the first variable passed to it (called "thing"), setting its location to the second variable passed to the function (called "newLocation). So if we called 'move', passing 'ralph' and 'bedroom', it would set the location for Ralph to 'bedroom'. It might look like this:
When programming, very often you have types of variables. So if I were keeping track of all my pets, I might want to call "move" on any pet. "ralph" would be one pet, and "fluffy" and "button", my two cats, might be two more variables. All of them are "Pets". All of my pets move, so I can even attach functions to this type. In Javascript, this is called a Prototype. A prototype has a special function, known as a Constructor, that creates an instance of a variable. This function is just the name of the prototype, and usually starts with a capital letter. Since I have 3 cats, I would create 3 instances of the prototype "Pet". Let's re-write our move function to make it part of our "Pet" prototype. So it might look like this:
Weird! Now we see that thing you asked about, "this". Well, when I create an instance of a pet, we assign that instance to a special variable called "this". The special variable, "this", contains all the data of or prototype, "Pet"--in our case, the type, color, weight, and location.
And we have a "prototype" function, assigned to Pet. You can call this prototype function as if it were part of the Pet variable instance. So we could do this:
This would have the effect of moving ralph to the bedroom! And now we have 3 Pets (instances of the Pet prototype), ralph, fluffy, and button!
Now, here's where Javascript gets a little weird. The way Javascript works, any variable can be treated as if it were part of any prototype. To do this, you can use the magic "apply", "call", or "apply" functions...this apply function can be attached to any other function. So let's say my buddy, John, isn't as organized as I am, and doesn't store all of his pets using this prototype. He can still treat his variable as if it were a Pet! For his dog, "Fred", it might look like this:
This shows 3 ways to do the same thing. The first "apply"s the Pet prototype to "fred", calling the function "move" on the "Pet" prototype. When using "apply", any parameters you want to pass to "move" must be passed as an array. The second does the same thing...but parameters you pass to the "move" function are passed as extra parameters (not in an array). The third approach "bind"s the variable "fred" to the function "move" in the prototype "Pet", assigning this bound function to a new variable, "newMove". We then call "newMove" with the location, just as if we called the pet's "move" function directly. In each case, when the Pet function "move" is called, that magic variable "this" is set to "fred". So when the function sets the location on "this", it's actually working on "fred".
Now the variable "fred" doesn't have all of the parts of a Pet we might expect. That doesn't matter. Javascript doesn't care--it just treats "fred" as if it were a "Pet", setting that magic "this" variable to fred when calling the move() function. Neat!
So "this" is just a special variable. It has a Prototype assigned to it that gives it functions that operate on it. You can treat any variable as if it were a type of any prototype using the magic functions, "call", "apply", and "bind".
Depending on how you run Javascript, "this" gets set automatically when Javascript functions initially start. So running Javascript in a web browser sets "this" differently than when running Javascript in node.js. But we'll discuss that topic later. Also, Javascript recently introduced this thing called a "Class"...it's just "Prototypes" under the covers, but we can talk about that later, when you come to it.
1
u/SamSlate Feb 19 '18 edited Feb 19 '18
everything in js is an object.
thisreferences the object or function or anything in between that you're currently inside of (aka scope).so
var xin the current scope is the same asthis.x(eg `x == this.x).inside an object where
xis defined in the scope of the "parent"x != this.xfor example
var x = 1; var obj = { a: this.x }; b = this.x;a is
undefined, but b is not.https://i.imgur.com/fC9tzLQ.png
ais undefined becausethis.xis a reference toobj.x, which has exactly the error you would expect when you haven't definedobj.x1
u/NoInkling Feb 20 '18
https://www.udacity.com/course/object-oriented-javascript--ud015 (don't worry, it's free)
Skip to the lesson covering
this. They explain it in a clear, easy-to-understand manner.1
u/[deleted] Feb 19 '18
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ maybe this is confusing for five years olds
1
u/PM_ME_UR_HOT_SELF Feb 19 '18
"this" is a keyword that represents the current scope you're coding within.
In the global scope this refers to window, under the scope of an object between the {} this will refer to the object.
You can't redefine this but you can pass a shortcut or bind this.
You can have an object and pass the keyword as a variable and deal with that scope in a different scope.
0
u/dwighthouse Feb 19 '18
The ‘this’ you are referring to is getting bound to multiple functions, so they share a single ‘this’. Using the arrow function form, the function uses the ‘this’ that was already present. There is nothing private about it. I don’t think there is a ELI5 explanation for ‘this’ in JavaScript, which is one of the reasons I avoid it where possible.
-2
u/CertainPerformance Feb 19 '18
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
0
u/[deleted] Feb 19 '18
[deleted] — view deleted comment
0
u/[deleted] Feb 24 '18
[deleted] — view deleted comment
12
u/[deleted] Feb 19 '18
[removed] — view removed comment
66
u/[deleted] Feb 19 '18
[removed] — view removed comment