Skip to content

Instantly share code, notes, and snippets.

@nodename
Created July 20, 2011 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nodename/1094495 to your computer and use it in GitHub Desktop.
Save nodename/1094495 to your computer and use it in GitHub Desktop.
Interesting use of 'finally' to slip some code in before a function returns
package
{
// end() is executed after the return statement but before the function returns!
public function aop(method:Function, begin:Function, end:Function):Function
{
return function(...args):*
{
try
{
begin();
return method.apply(null, args);
}
finally
{
end();
}
}
}
}
// originally from Andy Shang http://bbs.9ria.com/viewthread.php?tid=47399
package
{
import flash.display.Sprite;
public class AOPTest extends Sprite
{
public function AOPTest()
{
trace(aop(sum, begin, end)(3, 5));
}
/*
output:
begin
calculating...
end
8
*/
}
}
function sum(x:Number, y:Number):Number
{
trace("calculating...")
return x + y;
}
function begin():void
{
trace("begin");
}
function end():void
{
trace("end");
}
@nodename
Copy link
Author

Removed distracting use of prototype; not relevant to the demonstration

@nodename
Copy link
Author

A commenter on the 9ria thread had seen this pattern used in JavaScript to solve memory leaks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment