代码之家  ›  专栏  ›  技术社区  ›  fishbone

javascript原型继承和定义顺序

  •  1
  • fishbone  · 技术社区  · 15 年前

    我在做一件事 Actionscript 3.0到Javascript -转换器。
    我试图找到一种方法来规避定义顺序的问题,因为在AS中,先定义哪个包并不重要。令我惊讶的是,下面的代码可以工作,尽管 定义在 文学士 继承自 :


    javascript(示例输出)
    Function.prototype.inherit = function(base) {
       var empty = Function.prototype.inherit.empty;
       empty.prototype = base.prototype;
       this.prototype = new empty();
    }
    Function.prototype.inherit.empty = function() {};
    
    //order doesn't matter
    (function(undefined) {
       function BA() {}
       BA.inherit(A);
       BA.prototype.f1 = function() { return "success"; }
    
       function A() {}
       A.prototype.f1 = function() { return "fail"; }
       A.prototype.f2 = function() { return "success"; }
    
       var bA = new BA;
       console.log("test1: %s; %s", bA.f1(), bA.f2());
       console.assert(bA instanceof BA);
       console.assert(bA instanceof A);
    })();
    




    javascript(示例输出)
    
    //order plays a decisive role
    (function(undefined) {
       function CBA() {}
       CBA.inherit(BA);
       CBA.prototype.constructor = CBA;
       CBA.prototype.f3 = function() { return "success"; }
    
       function BA() {}
       BA.inherit(A);
       BA.prototype.constructor = BA;
       BA.prototype.f1 = function() { return "success"; }
    
       function A() {}
       A.prototype.f1 = function() { return "fail"; }
       A.prototype.f2 = function() { return "success"; }
    
       var cBA = new CBA;
       //this won't work. The compiler claims that cBA.f1 is not a function
       console.log("test2: %s; %s, %s", cBA.f1(), cBA.f2(), cBA.f3());
    })();
    



    我怎样才能避开这个问题?注意,我不会使用任何提供继承的库。
    如果有人告诉我ActionScript3.0是否支持相互导入/访问包,这将是一个很大的帮助,例如:
    动作脚本
    
    package my.pkg1 {
       class A {
       }
       class B extends my.pkg2.C {
       }
    package my.pkg2 {
       class C {
       }
       class D extends my.pkg1.A {
       }
    }
    

    谢谢。
    乌利

    0 回复  |  直到 4 年前