Reputation: 189
To keep my program running smoothly, I have to create objects only when I need them. In my case, I want to see if an object of an unspecified class is null, and if not, then call tell it to initialize. (I think "initialize" is the correct term, correct me if I am wrong)
if (someObject == null) {
someObject = new someObject.class()
}
Obviously, this code does not work. The idea seems right, but Actionscript does not agree with me. How can this be achieved?
Edit - Perhaps this will help to simplify (or complicate) the answer. I know that someObject
extends my class SuperClass
. Can I use a property from SuperClass
to instantiate someObject
?
Upvotes: 0
Views: 96
Reputation: 39456
I'm going to make an attempt at getting on the right track toward a useful answer.
Firstly, looking at your example:
if (someObject == null) {
someObject = new someObject.class()
}
I'm not sure what you're trying to convey here. If someObject
is null
, you cannot extract any information about anything from it. Even if you type someObject
e.g:
var someObject:Sprite;
You cannot access information about the fact that the property someObject
is expecting a Sprite
*
*You can use describeType()
to access the type if someObject
is a member of a class, but lets not go there.
If you want to be able to:
You can write something like:
var existing:Object = { };
function findOrMake(type:Class):*
{
var key:String = type.toString();
if(!existing.hasOwnProperty(key))
{
// We need to make a new instance of this class.
existing[key] = new type();
}
return existing[key];
}
Which can be used like:
var someObject:Sprite = findOrMake(Sprite); // Makes a new Sprite.
someObject = findOrMake(Sprite); // References the above Sprite.
Upvotes: 1
Reputation: 814
Don't name the instance with the exact name of the class you're instantiating.
If you do this:
var someobject;
if (someobject == null)
{
someobject = new someObject()
}
it works.
Upvotes: 0
Reputation: 4870
If you know what type someObject is supposed to be, it's easy:
var someObject:SomeClass;
if(someObject==null)
{
someObject = new SomeClass(); // creates an instance of the class
}
If you don't, you're making it hard for yourself. You'll have to rethink your design I guess.
Upvotes: 2