Colobot Wiki
Advertisement

Occasionally, a class method needs to know the reference to the instance it is acting upon. For example the instance might want to pass it's own reference to another function. An implicit reference name this is available to methods and this is a reference to the current instance.

public class MyClass
{
	int    m_int;
	string m_str;
	void MyFunction()
	{
		OtherFunction(this);
		m_int = 2;
	}
}


void OtherFunction(MyClass obj)
{
	message(obj.m_str);
}


extern void object::Test()
{
	MyClass item();
	item.m_str = "Hello";
	item.MyFunction();  // display "Hello"
}

You can also put this before a field name in a method but this is not necessary. In the example above in the method MyFunction() following two lines have strictly the same meaning:

	m_int = 2;
	this.m_int = 2;  // identical

In a method of the object class, you can also use this before a field name.

extern void object::Display()
{
	message(orientation);
	message(this.orientation); // same thing but
	                           // more explicit
}

However if a field name is hidden by a parameter declaration or a variable declaration you must use this. In the following example the name value of the parameter is the same as the name of the field value of the class MyClass, we must therefore write this.value in order to distinguish the field from the parameter.

public class MyClass
{
	int  value;
	void Put( int value )
	{
		this.value = value;
	}
}
Advertisement