2010-09-22 47 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.