动作脚本 3:将字符串变量作为函数调用
Action Script 3: Calling String variable as function
我有一个功能,
function tempFeedBack():void
{
trace("called");
}
当我像这样直接写函数名时,事件监听器工作得很好,
thumbClip.addEventListener(MouseEvent.CLICK, tempFeedBack);
但是,当我像这样将函数名称指定为字符串时,
thumbClip.addEventListener(MouseEvent.CLICK, this["tempFeedBack"]());
它不起作用!它说,TypeError: Error #1006: value is not a function.
有什么想法吗?
你得到那个错误是因为 this["tempFeedBack"]()
不是 Function
对象,它是 addEventListener()
函数的 listener
参数,此外,它什么也不是因为您的 tempFeedBack()
函数不能 return 任何值。
为了更好地理解,您所写的内容等同于:
thumbClip.addEventListener(MouseEvent.CLICK, tempFeedBack());
在这里您可以看到您已经将 tempFeedBack()
函数的 returned 值作为 listener
参数传递,它应该是一个 Function
对象,但是您的tempFeedBack()
可以return什么都没有!
所以,只是为了解释更多,如果你想让你写的东西起作用,你应该这样做:
function tempFeedBack():Function
{
return function():void {
trace("called");
}
}
但我认为你的意思是:
// dont forget to set a MouseEvent param here
function tempFeedBack(e:MouseEvent):void
{
trace("called");
}
stage.addEventListener(MouseEvent.CLICK, this["tempFeedBack"]);
// you can also write it
stage.addEventListener(MouseEvent.CLICK, this.tempFeedBack);
希望能帮到你。
我有一个功能,
function tempFeedBack():void
{
trace("called");
}
当我像这样直接写函数名时,事件监听器工作得很好,
thumbClip.addEventListener(MouseEvent.CLICK, tempFeedBack);
但是,当我像这样将函数名称指定为字符串时,
thumbClip.addEventListener(MouseEvent.CLICK, this["tempFeedBack"]());
它不起作用!它说,TypeError: Error #1006: value is not a function.
有什么想法吗?
你得到那个错误是因为 this["tempFeedBack"]()
不是 Function
对象,它是 addEventListener()
函数的 listener
参数,此外,它什么也不是因为您的 tempFeedBack()
函数不能 return 任何值。
为了更好地理解,您所写的内容等同于:
thumbClip.addEventListener(MouseEvent.CLICK, tempFeedBack());
在这里您可以看到您已经将 tempFeedBack()
函数的 returned 值作为 listener
参数传递,它应该是一个 Function
对象,但是您的tempFeedBack()
可以return什么都没有!
所以,只是为了解释更多,如果你想让你写的东西起作用,你应该这样做:
function tempFeedBack():Function
{
return function():void {
trace("called");
}
}
但我认为你的意思是:
// dont forget to set a MouseEvent param here
function tempFeedBack(e:MouseEvent):void
{
trace("called");
}
stage.addEventListener(MouseEvent.CLICK, this["tempFeedBack"]);
// you can also write it
stage.addEventListener(MouseEvent.CLICK, this.tempFeedBack);
希望能帮到你。