代码之家  ›  专栏  ›  技术社区  ›  mraaroncruz Stephen

在AS2中是否可以像在Javascript中一样使用闭包?

  •  2
  • mraaroncruz Stephen  · 技术社区  · 16 年前

    我想知道是否有可能在ActionScript2中创建一个闭包,就像在Javascript中一样。
    这不起作用:

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

    我试过其他方法,但都不管用。我希望这是可能的,因为如果我被迫使用AS2,我至少想从中得到一点乐趣:)

    2 回复  |  直到 16 年前
        1
  •  1
  •   Logic Artist    16 年前

    似乎您正在尝试使用actionscript,就好像它是javascript风格的面向对象编程一样。在javascript中需要使用闭包的原因是javascript缺少actionscript和其他经典语言的名称空间功能。这是在javascript中创建受保护的属性和方法的唯一方法。

    我强烈建议您为util对象创建一个外部类,这样它们就可以完全用于其他项目。但如果要创建单个临时对象,可以执行以下操作:

    var util = new Object();
        util.myUtils = new BlaBla();
        util.property = myUtils.blaBlaBla();
        util.init = function() {
          //Do some stuff here
        }
    
        2
  •  1
  •   mraaroncruz Stephen    14 年前

    本文阐述了如何使用匿名函数来传递作用域(这是我一开始真正想要的——我只是不知道;) http://studiokoi.com/blog/article/making_anonymous_functions_and_closures_work_in_actionscript_20