Another use for ‘this’

So just as I was looking over the lase post about ‘this’. I realized that I skipped one of the best uses for the infamous property of ‘this’. Enough talk, more actionscript (sorry terrible pun).

So imagine this. Lets say that we have class A which creates an instance of class B. Now lets say when want to store an instance of class A in class B so that you can call class A methods. For smaller apps this is can be an acceptable code structure. So how do you pass an instance of a class in that same class? You guessed it. this!

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class A 
{
	private var b:B;
 
	public function A()
	{
		b = new B(); //Creates instance of B class
		b.a = this; //this passes a reference of class A
		//to class B.  Now class B can call class A's
		//myCoolFunction.
	}
 
	public function myCoolFunction():Void
	{
		//Magic happens here. :)
	}
}

If you have any other handy uses for this (I’m sure there are), please let me know in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *