我正在尝试拥有一个更动态的函数,并希望允许函数实例名称,因为它输出的文本是可更改的。
例如
function example_function(url,instance_name){
instance_name.text = url;
}
example_function('www.example.com','url_txt');
example_function('www.another.com','more_txt');
这可能吗?
答案 0 :(得分:3)
是的,只需将字符串解析为实例所有者旁边的方括号即可。例如:
this[instance_name].text = url;
更多信息:
拿这个对象:
var obj:Object = {
property1: 10,
property2: "hello"
};
可以按照您的期望访问其属性:
obj.property1;
obj.property2;
或如上所述:
obj["property1"];
obj["property2"];
我建议使用像我这样创建的函数来加强你的代码:
function selectProperty(owner:*, property:String):*
{
if(owner.hasOwnProperty(property)) return owner[property];
else throw new Error(owner + " does not have a property \"" + property + "\".");
return null;
}
trace(selectProperty(stage, "x")); // 0
trace(selectProperty(stage, "test")); // error
答案 1 :(得分:0)
这绝对是可能的,但用这样的字符串做这不是最好的做法。相反,您可以传入对您尝试修改的变量的引用。
function example_function(url : String, instance : TextField) : void {
instance.text = url;
}
example_function("www.example.com", url_txt);
这为您提供了强大的输入,因此您可以在编译时告诉您是否在TextField上操作。如果不是,则会出现错误,因为“text”属性不存在。您将能够以这种方式更快地找到并追踪错误。
但是,如果必须使用字符串,则可以使用字符串键访问任何对象上的任何属性,如:
var myInstance = this[instance_name]
所以在你的例子中,你可以这样做:
function example_function(url : String, instance : TextField) : void {
this[instance_name].text = url;
}
example_function("www.example.com", "url_txt");