Is it possible to use closures in AS2 like in Javascript?
I am wondering if it is possible to create a closure in ActionScript2 like it is possible in Javascript.
This doesn't work:var util = function(){
var init = function(){
trace(this + ': util'); // i want to know this thing works!
var myUtils = new MyAS2Utils(); // load some stuff
var url = myUtils.getURLInSomeReallyCoolWay(); // really, this is all fluff isn't it?
myAwesomeButton.onRelease = function(){
getURL(url,"_blank");
}
}
// and return the goods
return {
init : function(){
init();开发者_如何学编程
}
}
}();
// now call the init funciton
util.init();
I have tried this other ways but it never works. I hope it's possible because if I'm forced to use AS2, I want to at least have a little fun with it :)
thanks! aaronIt appears you are trying to use actionscript as if it were javascript-style object oriented programming. The reason you need to use closures in javascript is because javascript lacks the namespacing abilities of actionscript and other classical languages. Its the only way to create protected properties and methods in javascript.
I highly recommend you create an external class for your util objects, that way they are completely reusable for other projects. But if you want to create a single, temporary object you can do this:
var util = new Object();
util.myUtils = new BlaBla();
util.property = myUtils.blaBlaBla();
util.init = function() {
//Do some stuff here
}
This article articulates how one can use anonymous functions to pass around scopes - which is what I was really looking for in the first place - I just didn't know it ;) http://studiokoi.com/blog/article/making_anonymous_functions_and_closures_work_in_actionscript_20
精彩评论