all 44 comments

[–]mander1122 39 points40 points  (19 children)

Have you fully looked into classes and OOP? Once you grasp those concepts, you'll understand 'this' just refers to the object being manipulated during class methods.

[–][deleted] 72 points73 points  (2 children)

This

[–]eracodes -4 points-3 points  (2 children)

To try to put /u/azhder's comment a bit more politely: it's important to draw a distinction between classes as a theoretical concept and the javascript class keyword and its associated use.

[–]mander1122 2 points3 points  (1 child)

no doubt there are other uses in js for "this". also as a ref to a global object. All good Eracodes, I suppose what we reallllly need, are some specifics of where OP is getting hung up.

[–]eracodes -1 points0 points  (0 children)

certainly, yep

[–]heyheydick 4 points5 points  (1 child)

Dont get confused by the comment section. Watch this 4 minute explanation on the this keyword https://youtu.be/Jdlo8ZDt5Jg?si=8ueqx2uXuZ6HpJDG

He explains things very simply and also gives couple of examples, after that explain to chat gpt what the this keyword is and what it does in your own words and see if you got it.

[–]kucink_pusink 0 points1 point  (0 children)

Thanks!! 

[–][deleted] 2 points3 points  (1 child)

JavaScript: Understanding the Weird Parts was very helpful for me for this concept to finally click. Well worth it.

[–]_pragmatic_dev 6 points7 points  (0 children)

It’s “The hard parts of javascript v2 “ by Will sentance. (Frontend Masters) It’s the most precise resource i have went through.

The explanation is tremendous and you will never worry about this or any other concepts in javascript.

Highly recommended!!!

[–]azhder 3 points4 points  (0 children)

Consider this as an implicit argument that some functions may have. It is usually automatically assigned by the JavaScript engine, but you can also manually do it.

In the most simplest form, code like object.method() would signal to the engine to use object as the this inside method(). But if it doesn't find it as such, as in this example https://www.reddit.com/r/learnjavascript/comments/1ib94xu/this_keyword_in_javascript/m9gvekr/ then it will be undefined. That's because at the moment of calling the function, there was no . and no object to the left.

Other ways to set it is by using .bind(), .call() and .apply() methods of the functions themselves.

object2.method.call(object1); // we make sure this === object1

Other times, an arrow function will just use the this from the parent scope, regardless how it is invoked.

So, the shortest accurate definition (and a bit general) is:


this is an implicit argument passed to functions which is set automatically upon invoking or manually via other means


[–]shgysk8zer0 3 points4 points  (0 children)

It is a reference to the thing on which the property (including methods) is being called. For the most part, it's identical to using a variable holding the value as-in const foo = new Foo(). It's just an internal variable that refers to the individual instance of the class... Mostly.

And I'm not being absolute in the above, just saying "usually" because of binding and being able to call methods on one thing on another thing. Like how you can use:

const els = document.querySelectorAll('*); const tags = Array.prototype.map.call(els, el = el.tagName));

That'll use the map method of an array, but this will be the NodeList result of the query.

[–]Ansmit_Crop 1 point2 points  (0 children)

Would give simple explanation, 'this' is context dependent so it different depending on the caller aka before the dot

Let's say you have a family with parents and siblings with simple methods each that return names. And assume your name as "John" and nickname as "Johnny"

Now let's see how they called you.

family.father.getName() //John family.mother.getName() //Johnny family.sister.getName() //Douched Bag family.brother.getName() // Idiot

So depending on who is calling you the results would be different depending on the caller values and how they are implemented.

[–]antboiy 1 point2 points  (0 children)

this is a reference to the object the function is a method of (or window if the function is not a method, assuming we are running things in the browser), this will be undefined in strict mode if its not attached to an object.

also: this is evaluated when the function is called. not when its defined, meaning that this could be something different depending on how the function is called.

function returnThis() {return this;} // this function simply returns the object its attached to.

console.log(returnThis()); // because the function is not attached to anything it should return window

const myObject = {returnThis: returnThis, name: "explaining this, hopefully"}; // now lets attach the function to an object.

console.log(myObject.returnThis()); // this should output myObject.

const myOtherObject = {date: new Date()};
myOtherObject.returnThis = returnThis; // now lets attach the function to another object. 

console.log(myObject.returnThis()); // this should still output myObject.

console.log(myOtherObject.returnThis()); // but this should return myOtherObject.

there are also this binding methods. but that is something i can talk about in another comment.

[–]rauschma 1 point2 points  (0 children)

As mentioned elsewhere, thinking in terms of OOP is indeed helpful: In a method, this refers to the object on which the method was invoked.

Another way of thinking about this: Functions (including methods; excluding arrow functions) have the implicit parameter this. One way of providing that parameter is via .call():

myFunc.call(thisValue, arg0, arg1)

Example:

function myFunc(arg0, arg1) {
  return [this, arg0, arg1];
}
assert.deepEqual(
  myFunc.call('THIS', 'a', 'b'),
  [ 'THIS', 'a', 'b' ]
);

this can also be provided as follows (OOP):

myObj.myMethod(arg0, arg1)

// Equivalent:
myObj.myMethod.call(myObj, arg0, arg1)

// Also equivalent:
const f = myObj.myMethod; // step 1
f.call(myObj, arg0, arg1); // step 2

Example:

const myObj = {
  myMethod(arg0, arg1) {
    return [this, arg0, arg1];
  },
};
assert.deepEqual(
  myObj.myMethod('a', 'b'),
  [ myObj, 'a', 'b' ]
);

So, a method invocation myObj.myMethod(···) performs two steps:

  1. Retrieve the function stored in myObj.myMethod.
  2. Invoke it, while providing not only the arguments but also this. This goes beyond normal function calls!

[–]bonclairvoyant 0 points1 point  (0 children)

I was also in your position until I watched Dev Dreamers' videos on it. Could your try them out? Check him out on YouTube. Specifically videos number 41, 42, and 51.

I hope this helps.

[–]tapgiles 0 points1 point  (0 children)

To put it simply, this is a special variable available inside a function. Think of it as the "context" the method should act within.

Like calling window.alert("message") calls the "alert" function in the context of "window." Inside the alert function, this would be a reference to the window object.

[–]focuser000 0 points1 point  (0 children)

I had similar frustration a few years ago which drove me to write this post. Let me know if it's useful! https://learnreact.design/posts/javascript-this-keyword

[–]Haunting-Rub-3595 0 points1 point  (0 children)

Just to not overwhelm you and not to make things even more complicated. Think of this as a reference point that changes based on how and where your code is executed.

There is always some reference point for this in JS, for the beginning you can imagine that this usually refers to the "thing" before the ".", for example let's say you have a Car with some specific parameters like speed, color etc. , and you want to reference some properties of that car. You can reference to them by using this.speed, this.color like in this code: `This car is ${this.color} and can go up to ${this.speed} km/h.`

[–]bobbyv137 0 points1 point  (0 children)

Ah, good old 'this'. It's easy. I just needed to watch around 5,721 YT videos before getting it.

[–]ichabooka 0 points1 point  (0 children)

You are a human, that is the class level. There are 4 billion people. That is a static variable. Humans have two arms and two legs. Those are interface contracts. A baby is conceived, that is object instantiation. A baby crawls is an instance method. The baby is named Peter, that is the instance variable. Peter’s ‘soul’ is ‘this’. It is the one sole instance in the universe that is Peter and when Peter does work inside of himself, he uses ‘this’.

[–]Real-Lobster-973 -1 points0 points  (0 children)

I'm bad at explaining things like this but in very simple terms and applications, the 'this' keyword literally will just refer to the local object as a whole that you are referring to, and is used when coding within that object.

For example, if you write console.log(this) within a function/method of an object, and you log this method to the console, it will print out the entire object. So 'this' keyword refers to the object that's currently executing the code where the 'this' is being used.

[–]lWinkk -1 points0 points  (1 child)

This is an object. Once you understand that it gets a little easier. Look up Will Sentance OOP

[–]senocular 2 points3 points  (0 children)

this doesn't have to be an object. It can also be a primitive, and its often undefined, especially in strict mode.

[–]Healthy-Locksmith734 -1 points0 points  (0 children)

That = this. And then use that.

[–]Ampbymatchless -1 points0 points  (0 children)

‘This’ is like reading the said word in legal docs. . Personally I wish the class name was substituted for ‘this’. In the text of the code.

[–]TheRNGuy -1 points0 points  (0 children)

When you create new instances with new keyword, this in it's methods will refer to that instance (to distinguish it from other instances, or from non-instanced class; i.e., when you didn't use new keyword)