Simple question about 'this' keyword

For example:


if I call the keyword this inside this myMethod it(this) will refer to myInstance or what?

I’m a bit confused about this.

Thanks from now!


The keyword this is indeed a reference to the object executing a member function. It’s not necessary to use it in most cases, as that reference is used as well without the keyword. You should use when, for instance, a variable member of the class and a variable argument of a function member of that class have the same name. Maybe that code can make it clearer :

private class MyObject
    public string name = "No name yet";
    public void HelloTheWorld(){ print( "Hello, my name is " + ); }
    // This function will do exactly the same
    public void HelloTheWorld2(){ print( "Hello, my name is " + name ); }

private class PutMeOnAGameObject : MonoBehaviour
    private void Awake()
        MyObject myObject = new MyObject(); = "John";
        myObject.HelloTheWorld(); // Hello, my name is John
        myObject.HelloTheWorld2(); // Hello, my name is John

In C#: It will refer to the MonoBehaviour that is instantiated. ie: The component that lives in its container GameObject. So, yes, this would refer to myInstance, assuming myInstance was a reference to said component/MonoBehaviour.

In JS: Someone else will have to answer that, as I am not sure but it probably works the same. :slight_smile: