简体   繁体   English

动作脚本3:将String变量作为函数调用

[英]Action Script 3: Calling String variable as function

I have a function, 我有一个功能,

function tempFeedBack():void
    {
        trace("called");
    }

and event listener works perfect when I write function name directly like this, 当我像这样直接编写函数名称时,事件监听器就可以完美工作,

thumbClip.addEventListener(MouseEvent.CLICK, tempFeedBack);

But, when I give the function name as string like this, 但是,当我像这样给函数名称指定字符串时,

thumbClip.addEventListener(MouseEvent.CLICK, this["tempFeedBack"]());

It is not working! 它不起作用! It says, TypeError: Error #1006: value is not a function. 它说, TypeError: Error #1006: value is not a function.

Any ideas? 有任何想法吗?

You got that error because simply this["tempFeedBack"]() is not a Function object, which is the listener parameter of the addEventListener() function, in addition, it's nothing because your tempFeedBack() function cannot return any value. 之所以会出现this["tempFeedBack"]()错误,是因为this["tempFeedBack"]()不是Function对象,它不是addEventListener()函数的listener参数,此外,它什么也没有,因为您的tempFeedBack()函数无法返回任何值。

To more understand that, what you have wrote is equivalent to : 要进一步了解,您写的内容等同于:

thumbClip.addEventListener(MouseEvent.CLICK, tempFeedBack());

Here you can see that you have passed the returned value of your tempFeedBack() function as the listener parameter which should be a Function object, but your tempFeedBack() can return nothing ! 在这里,您可以看到已将tempFeedBack()函数的返回值作为listener参数传递,该参数应该是Function对象,但是tempFeedBack()不能返回任何内容!

So, just to explain more, if you want that what you have wrote work, you should do something like this : 因此,仅需解释一下,如果您想要自己编写的作品,则应该执行以下操作:

function tempFeedBack():Function 
{
    return function():void { 
            trace("called");
        }
}

But I think that what you meant is : 但是我认为您的意思是:

// 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);

Hope that can help. 希望能对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM