开发者

What's an example of calling a function through a reference?

开发者 https://www.devze.com 2023-02-08 11:37 出处:网络
What\'s an example of calling a function through a refer开发者_C百科ence (as opposed to directly)?If I understand the question, you want something like this:

What's an example of calling a function through a refer开发者_C百科ence (as opposed to directly)?


If I understand the question, you want something like this:

function myFunction():void { trace("calling my function!"); }
var functions:Array = [myFunction];

functions[0](); // traces "calling my function!"

The idea being that every function is also an object. When you have myFunction(), if you treat "myFunction" as a variable (note: no ()'s) then you can pass around a reference to that function. This is how, for instance, callbacks work.

For example:

this.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(e:MouseEvent):void {
trace("CLICK!");
}

in your addEventListener call, you're passing a reference to your clickHandler function. Flash then knows that whenever this object receives an event of type MouseEvent.CLICK, it should call the referenced function (in this case, clickHandler).

Does that make sense?


in this answer the Reciever class gets a reference to a function through constructor and calls it through this reference

0

精彩评论

暂无评论...
验证码 换一张
取 消