2010-09-22 74 views
0

以下是关于js中的oop的一些问题(代码如下)。javascript中的多继承

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

我想我应该澄清一下我的问题:js中多继承的缺点是什么?为什么变量a在全球范围内? – plehoux 2010-09-22 15:10:34

+2

然后把这个问题 - 使用编辑按钮 – 2010-09-22 15:14:46

回答

3

您需要声明变量avar声明,以使本地的功能。

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

你不能。当你这样做

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

你只是改变prototype指向的对象。所以C用于从继承,但现在它继承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

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

多的传承不是在JavaScript支持。你所做的只是让C继承B而不是A.