【问题标题】:Multiple inheritance in javascriptjavascript中的多重继承
【发布时间】:2011-04-15 19:10:06
【问题描述】:

这里有一些关于 oop in js 的问题(问题在下面的代码中)。

<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>

【问题讨论】:

  • 我想我应该澄清一下我的问题:js中多继承的缺点是什么?为什么变量 a 在全局范围内?
  • 然后把它放在问题中 - 使用编辑按钮

标签: javascript oop multiple-inheritance


【解决方案1】:
C.prototype = new A();
C.prototype = new B();

javascript 不支持多重继承。你所做的只是让 C 继承自 B 而不是 A。

【讨论】:

    【解决方案2】:

    你不能。当你这样做时

    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 的 prototype 对象的任何更改都不会传播到 C。

    【讨论】:

      【解决方案3】:

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

      function A(){
        var a = 'a - private FROM A()';
        this.a = 'a - public FROM A()';
        this.get_a = function(){
          return a;
        };
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        • 2015-10-14
        • 2013-09-01
        • 2013-01-12
        • 1970-01-01
        相关资源
        最近更新 更多