views:

89

answers:

1

I have a Rect object that I'd like to create and set its properties only once. After that, I want to just modify its properties since it already exists. This is my general idea

if(theRect == undefined){

  Alert.show("creating");

  var theRect:Rect = new Rect();
  //then set properties
  addElement(theRect); //then add it using addElement because addChild() does not work

} else {

  Alert.show("updating");

  //no need to create it since it's already been created
  //just access and change the properties

}

I tried several ways and combinations for the if conditional check:

if(theRect == undefined){
if(theRect == null){
declaring and not declaring `var theRect:Rect;` before the if check
declaring and instantiating to null before the if check `var theRect:Rect = null;` 

but can't get the desired effect. Everytime this code block runs, and depending on which version I've used, it either gives me a "can't access null object" error or the if statement always evaluates to true and creates a new Rect object and I get the "creating" Alert.

What's the right way of creating that Rect but only if doesn't exist?

+1  A: 

You have some scoping issues in the code you presented.

What I think you want to do is:

var theRect:Rect;

...

if(theRect == null)
{
    theRect = new Rect();
    ...
}
...

You need to first declare theRect, but you don't have to create it. You can instantiate it lazily later by checking if it is null.

The way you have it set up, you created a local version of theRect inside your if statement that would not be visible elsewhere. You will also get an error trying to access theRect if you did not declare it beforehand.

CookieOfFortune
That was one of the things I've tried, creating the variable before the if check, and I still had problems with. But it was indeed a scoping issue, and I now see why, it's because all this is in a method and the declaration was being repeated too, silly me. Moved it out now and all is good. Thanks for the hint.
touB