在flex中,如何检查变量是否存在?我尝试过使用
if (this['some_variable'] != undefined) {
//do something
}
运行时错误表示属性some_variable
不存在。我已使用null
而不是undefined
进行了检查,但仍然存在相同的错误。
请帮忙。
[编辑]
根据我使用的回复this.hasOwnProperty('variable_name')
。我发现,如果true
variable_name
为public
,则返回false
,private/protected
{{1}}。如何检查私有变量?
答案 0 :(得分:8)
有两种方法:
if ("some_variable" in this) {
//do something
}
它使用in
operator。
和
if (this.hasOwnProperty("some_variable")) {
//do something
}
请参阅documentation about hasOwnProperty()
。
如果获取有关私有/受保护属性的信息,那么您无法通过Flash Player的当前状态获取此信息。我想,唯一可能的方法是某种运行时字节码操作。但据我所知,还没有人实现它。
但我有一个关于获取有关私有/受保护属性的信息的问题:您需要它的目的是什么?这些属性/方法的本质是你无法调用它们。即使你知道他们的存在。
答案 1 :(得分:6)
您可以使用
if (this. hasOwnProperty("some_variable")) {
//access the variable inside
}
答案 2 :(得分:2)
if (this.hasOwnProperty('some_variable')) DO_IT_!()
说明:
this['some_variable']
尝试评估实例属性some_variable
的值。如果没有这样的属性,您将收到此错误。
要测试特定对象的属性是否存在,请使用hasOwnProperty
或将您的条件包装在try/catch
块中或使用if ('some_variable' in this)
。
通常在类文件中创建一个对象属性:
public class MyClass {
public var myProperty : String = "ich bin hier";
}
然后在类中引用该属性:
trace (myProperty);
trace (this.myProperty);
也可以使用数组语法[],但如果未定义属性,则会抛出错误。
trace (this['myProperty']);
最后!如果您声明您的类是动态的,即使该属性不存在,也可以使用数组语法。
public dynamic class MyClass {
public function MyClass() {
trace (this["never_declared_property"]);
}
}