3
votes

In flex, how to check if a variable exists? I have tried using

if (this['some_variable'] != undefined) {
    //do something
}

There is a run time error saying the property some_variable does not exists. I have checked with null instead of undefined, still the same error.

please help.

[EDIT]

Based on the replies I have used this.hasOwnProperty('variable_name'). I found that its returning true if variable_name is a public but false if its private/protected. How to check for a private variable?

3
set a breakpoint and check the Variables view - assuming you're using Flash Builder. - Chunky Chunk
hasOwnProperty() only works for those fields that are made public. There is nothing you can do in AS3 to perform intraspection to reveal private members. If this absolutely a requirement for you, switch over to AS2 where everything is public. - Mark Lapasa

3 Answers

8
votes

There are two ways for that:

if ("some_variable" in this) {
    //do something
}

It uses in operator.

And:

if (this.hasOwnProperty("some_variable")) {
    //do something
}

See documentation about hasOwnProperty().

What about getting information about private/protected properties the situation is that you can't get this info with the current state of Flash Player. The only possible way, I suppose, is some kind of runtime bytecode manipulation. But as far as I know nobody implemented it yet.

But I have a question about getting info about private/protected properties: for what purpose you need it? The nature of these properties/methods is you can't call them. Even if you know about their existence.

6
votes

You can use

if (this. hasOwnProperty("some_variable")) {
    //access the variable inside
}
2
votes

if (this.hasOwnProperty('some_variable')) DO_IT_!()

Explanation:

this['some_variable'] tries to evaluate the value of the instance property some_variable. If there is no such a property, you will get this error.

To test if a property exists for a particular object use hasOwnProperty or wrap your condition in a try/catch block or use if ('some_variable' in this).

Usually you create an object property in a class file:

public class MyClass {
   public var myProperty : String = "ich bin hier";
}

Then you refer to that property within the class:

trace (myProperty);
trace (this.myProperty);

Using the array syntax [] is also possible but will throw the error if the property is not defined.

trace (this['myProperty']);

And finally! If you declare your class to be dynamic you might use the array syntax even if the property does not exist.

public dynamic class MyClass {
   public function MyClass() {
       trace (this["never_declared_property"]);
   }
}