x


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!

more ▼

asked May 03 '12 at 02:53 AM

GutoThomas gravatar image

GutoThomas
593 32 46 47

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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. :)

more ▼

answered May 03 '12 at 03:24 AM

chainedlupine gravatar image

chainedlupine
122 2 2 3

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!

May 03 '12 at 03:38 AM GutoThomas
(comments are locked)
10|3000 characters needed characters left

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
    }
}
more ▼

answered May 03 '12 at 03:32 AM

Berenger gravatar image

Berenger
11k 12 19 53

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x203
x55
x8

asked: May 03 '12 at 02:53 AM

Seen: 619 times

Last Updated: May 03 '12 at 03:38 AM