- Home /
Simple question about 'this' keyword
For example:
myInstance.myMethod();
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!
Cheers!
Answer by chainedlupine · May 03, 2012 at 03:24 AM
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. :)
Thanks for both answers! Think was what I thought it was. To mark the correct one I'll use the criterion of who answered first, but thanks for both replies!
Answer by Berenger · May 03, 2012 at 03:32 AM
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.name ); }
// 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();
myObject.name = "John";
myObject.HelloTheWorld(); // Hello, my name is John
myObject.HelloTheWorld2(); // Hello, my name is John
}
}