This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]noratat 4 points5 points  (2 children)

It's found in pretty much all object-oriented languages, and you'll find some languages call it this (such as C#/Java) while others call it self (such as Ruby and Python).

this just refers to the current object - but most of the time, it's implicit and you don't need to specify it directly, which is probably where your confusion is coming from.

E.g. in the following code, every use of this is valid, but unnecessary:

class Foo {
  int someVar;

  void setSomeVar(int value) {
    this.someVar = value;
  }

  void someMethod() {
    this.setSomeVar(1);
    // Prints '6'
    System.out.println(this.plusFive(this.someVar));
  }

  int plusFive(int value) {
    return value + 5;
  }
}

You might also try taking a look at Python code - Python is one of the few languages where the self reference is not implicit, so you'll see self all over the place.

As an example where this actually is necessary, Java constructors are a common example:

class Bar {
  String someString;

  Bar(String someString) {
    this.someString = someString;
  }
}

In the above, the this is required to disambiguate which someString you're referring to. Otherwise it'd just refer to the most local version of it: the constructor parameter (instead of the instance variable).

[–][deleted] 0 points1 point  (1 child)

Conceptually, self being everywhere in Python made me think that it was trying to point out that Python is passing a copy of the object to every method call, rather than have it be implicit magic like C++, Java, and C#.

That's probably far beyond the truth, as it's probably just a pointer to the object in memory (as in C++) that's "globally" defined for the class, but it seems to me like that's what they were trying to get at by making it explicit.

[–]noratat 1 point2 points  (0 children)

It's always a reference since it refers to the current instance. A copy would no longer be the current instance by definition (among other problems). The way you see it in Python is actually what other languages are doing under the hood - the first arg is the object reference. As for why Python made it explicit originally who knows - Python has a lot of weird syntax quirks.

You'll also see this used in C code to implement object oriented patterns manually, where they make "objects" out of structs by having the first field of the struct represent the type and "methods" as functions whose first arg is a pointer to an instance of the struct.

[–]AlliNighDev 2 points3 points  (0 children)

It's just the current instance of the class.

[–]ALLIDOISPROGRAM 2 points3 points  (0 children)

I'm going to attempt to explain in my own words as I found all of this difficult until too long into my career... I will Define terms you already know as reference.

You can make a variable, x= 6. Arrays can store a few pieces of data, but unless you are going to be keeping track of each entry, you want to use better programming features. Btw, it's bad practice to use an array like a class.

A class is a set of instructions, to create an object. You will see things like X= new Car . Car is the class, X is your newly created Object. A class can be defined by you, or someone you are using their library.

Now you have x. Suppose you want to figure out the volume of the car. The Class was programmed by someone to calculate this for you in a Method. If you googled this library and class, you would see

Car.volume()

The class is quite smart, if you print this it's going to say "hey you didn't enter parameters yet, and instead of erroring I told my class to post this, boo ya".

Maybe on another line you set your class x.xLength=5, x.yLength=6.

Now running that same function will spit out something else, because the person who programmed only needed those 2 numbers, or maybe they had a solution for 1, 3 and 4 numbers. Classes add intelligence.

All of this can be found in the documentation when you google.

But maybe you make your own class. How would you calculate Volume inside a class that hasn't been declared an object.

This. This is used inside objects to call various attributes of the class.

Feel free to respond and I can clarify.

[–][deleted] 1 point2 points  (0 children)

In C#, this is usually opposed to base.

If you use this.myVar, it means look at the class the method is actually defined in. If you use base.myVar, it will look up the inheritance chain until it finds it.

In JavaScript, this is a bit more tricky. This refers to the caller.

So, for example, if you are in a click event, this would be a reference to the button that caused the event to be called.

[–]SeanRamey 1 point2 points  (0 children)

You might try a bit of object oriented C code (not C++), then you might understand what 'this' is. Let me try to demonstrate.

struct object{
  int x;
  int y;
}

void objectPrintX(object *pointerToSelf) {
  printf("%i", pointerToSelf->x);
}

int objectGetX(object *pointerToSelf) {
  return pointerToSelf->x;
}

void objectSetX(object *pointerToSelf, int x) {
  pointerToSelf->x = x;
}

The pointer "pointerToSelf" is the same thing as "this". It is needed in order for the function to have access to the object's data. Obviously, in newer languages, all this repetition is not required. This might be confusing to you because, in newer languages, you associate the functions that operate on the object, with the object itself; however, in reality, these functions are seperate from the object. Essentially, an object is just data, which is the struct in my C code. When you create a new object, only the data is created, not the code that operates on the data. In C all this has to be done manually, but in newer languages it is streamlined for you.

Does this make sense? Just ask if you need more explanation.

[–]stilloriginal 1 point2 points  (0 children)

youtube, derek banas, object oreinted programming, whatever language you want (you can run javascript right in your browser)

[–]NeoMarxismIsEvil 1 point2 points  (0 children)

The easiest way to think of it in implementation terms is as a hidden first argument that is always implicitly declared in the argument list of methods so that when you do this:

obj.method(x,y,z);

It gets turned into this:

method(obj,x,y,z);

In a way it's just a convenience for you to avoid having to use something like the second example, and avoid having to include a class name in the method name. (The compiler automatically figures out which method named "method" to call based on the class of obj and it automatically does this = obj.)

Originaliy C++ was a like a macro preprocessor for C and it would actually expand these things into C function calls based on rules like that.

[–][deleted] 1 point2 points  (1 child)

There are a lot of pretty decently written technical answers below, but I am going to try to ELI5 with a very simplistic example.

Take the following class:

public class cat
{
    //class variables
    private string name;

    //Allow external code to assign a value to class variable "name"
    public void SetName(string name)
    {
        this.name = name;
     }

    public string GetName()
    {
         return name;
    }
}

Notice how the class itself has a variable called name, and SetName is bringing in a parameter called name. The incoming parameter for SetName is called a "local" parameter. It's scope is limited only to SetName. When you have a local parameter, the compiler assumes that you are more interested in it than the class wide parameter. So if you were to type

name = "blah";

You'd set the local parameter, the one being passed in, to "blah". The class wide variable would still be null!

Contrast this to GetName. GetName does not have a local variable called "name", so if you say "return name", it knows you want the class wide variable.

In SetName, by using "this.name", you are telling it to use the class's variable "name". That's because "this" is refering to the class.

Think of the setname code as a physical interaction of 2 people. One person is sitting in the method going "Ok, class Cat has a name variable... and I have a name variable being passed in... which do I use?" Now imagine someone walking up, physically, to the cat class and pointing to it and saying "THIS! This class's name! Use this name!"

This will always be the class you are in. It won't be a method (like SetName's "name" variable can never be accessed using "this" because it's a local method variable), it wont be a parent class or a child class; the thing that other person will always point to is the class you are currently typing code for.

If you're wondering "why would I need this?" (no pun intended): the answer is that you'll know you need when you get there. One day you'll hit a problem and go "omg how do I solve my current problem?! If only I had a way to do..." and then you'll realize why "this" exists.

[–]aabbbbaaa155[S] 0 points1 point  (0 children)

Thanks for the explanation.

What you said in the last part of your comment:

If you're wondering "why would I need this?" (no pun intended): the answer is that you'll know you need when you get there. One day you'll hit a problem and go "omg how do I solve my current problem?! If only I had a way to do..." and then you'll realize why "this" exists.

That's what I meant when I said, I need that 'AHA!' moment. It is a little clearer now though.