Created
July 20, 2011 07:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
} |
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
Removed distracting use of prototype; not relevant to the demonstration