javascript中的多重继承

ple*_*oux 0 javascript oop multiple-inheritance

这是关于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>
Run Code Online (Sandbox Code Playgroud)

sle*_*man 7

C.prototype = new A();
C.prototype = new B();
Run Code Online (Sandbox Code Playgroud)

javascript中不支持多重继承.你所做的就是让C继承自B而不是A.


Moo*_*Goo 6

你不能.当你这样做

C.prototype = new A();
C.prototype = new B();
Run Code Online (Sandbox Code Playgroud)

您只是更改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];
Run Code Online (Sandbox Code Playgroud)

现在你有了A和B的属性/方法,但是你没有真正的继承,因为prototype对B 的对象的任何更改都不会传播到C.