PDA

View Full Version : getting a return value from an instantiated class object


Jerico
11-07-2007, 02:57 AM
Hi all...

I'm building a class object that has no public methods, but I need it to return a value upon instantiation. Is this possible? I realize that a constructor function can't have a return type, but it can accept parameters, so how would I go about this?

var myObject:myClassObject = new myClassObject(1,2,3,4);
trace(myObject);

Flash Gordon
11-07-2007, 03:45 AM
can't.

you should probably just make some static method of some class.

Jerico
11-07-2007, 02:17 PM
Damn - I had an instance method set up to do this, and then i thought I would be smart and remove it since the class will only ever return one value.

If I make it a static method, will I still be able to create multiple instances of the object?

Flash Gordon
11-07-2007, 05:37 PM
Your point is you don't need instances. But you can use it multiple times, just like Math.random() can be used over and over. So can your static class method.

ryryguy
11-07-2007, 05:57 PM
If I'm understanding your needs correctly, then Flash is right, a static method - or perhaps just a static property (getter/setter optional) - would make the most sense.

But FYI, it's possible to effectively pass a return value through a parameter, if it's a type that is passed by reference. Simple types like ints are not passed by reference, but Objects, Arrays, and Dictionaries are.

Here's an example. The array argument is changed but the change to the integer argument doesn't last after the function returns. (The function isn't a constructor but it returns void... the same should work for a constructor too.)

var array:Array = [];
var integer:int = 0;

trace(array.length);
trace(integer);

function setArgs(a:Array, i:int):void
{
array.push("Hey!");
array.push("there!");
i = 5;
}

setArgs(array, integer);

trace(array.length); // 2
trace(array[0]); // "Hey!"
trace(integer); // 0