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

javascript中的多重继承

  •  0
  • plehoux  · 技术社区  · 16 年前

    下面是一些关于js中oop的问题(下面代码中的问题)。

    <html>
        <script>
        function A(){
          a = 'a - private FROM A()';
          this.a = 'a - public FROM A()';
          this.get_a = function(){
            return a;
          }
        }
    
        function B(){
          this.b = 'b - private FROM B()';
          this.a = 'a - public FROM B() ';
        }
    
        C.prototype = new A();
        C.prototype = new B();
        C.prototype.constructor = C;
        function C() {
          A.call(this);
          B.call(this);
        }
    
        var c = new C();
    
        //I've read paper about oop in Javacscript but they never talk 
        //(the ones have read of course) about multiple inheritance, any 
        //links to such a paper?
    
        alert(c.a);
        alert(c.b);
        alert(c.get_a());
    
        //but
    
        //Why the hell is variable a from A() now in the Global object?
        //Look like C.prototype = new A(); is causing it.
    
        alert(a);
    
        </script>
    </html>
    
    3 回复  |  直到 16 年前
        1
  •  3
  •   Golmote Kinoko    16 年前

    您需要声明变量 a var 语句,以使其成为函数的局部。

    function A(){
      var a = 'a - private FROM A()';
      this.a = 'a - public FROM A()';
      this.get_a = function(){
        return a;
      };
    }
    
        2
  •  7
  •   slebetman    16 年前
    C.prototype = new A();
    C.prototype = new B();
    

        3
  •  6
  •   MooGoo    16 年前

    你不能。当你这么做的时候

    C.prototype = new A();
    C.prototype = new B();
    

    你只是在改变 prototype 指向。所以C以前是从A继承的,但现在是从B继承的。

    C.prototype = new A();
    
    for (var i in B.prototype)
      if (B.prototype.hasOwnProperty(i))
        C.prototype[i] = B.prototype[i];
    

    现在您将拥有来自A和B的属性/方法,但实际上没有继承,因为对 原型 B的对象不会传播到C。