2016-03-14 58 views
-1

我正在使用下面的代碼。我的代碼出錯了。現在我得到「這是aB」,但我需要在我的輸出控制檯上構造相關的輸出。第一個是「這是aA」,第二個是「這是aB」,第三個控制檯是「這是aC」。多繼承控制檯輸出

function A() { 
    this.name = "A"; 
} 

A.prototype.a = function() { 
    console.log("this is a"+this.name); 
} 

function B() { 
    this.name = "B"; 
} 

B.prototype.b = function() { 
    console.log("this is b"+this.name); 
} 

function C() { 
    this.name = "C"; 

    A.call(this); 
    B.call(this); 
} 

C.prototype = Object.assign({}, A.prototype, B.prototype); 
C.prototype.constructor = C; 

C.prototype.c = function() { 
    console.log("this is c"+this.name); 
} 

var x = new C(); 

x.a(); //this is aB 
x.b(); //this is bB 
x.c(); //this is cB 
+2

您引用的輸出不是該代碼的輸出。你已經展示了三次「aB」。事實上,輸出是'aB','bB'和'cB'(如果我們忽略了因爲記錄調用方法的結果而被記錄的未定義記錄,但這些方法不會返回任何東西)。 –

+0

我已修復了上述評論中提出的問題,僅供參考。 –

回答

1

在所有三個構造this是指相同的對象:由操作者new創建的一個。那一個對象只能有一個name屬性。所以你最後調用的那個構造函數將會「獲勝」,並且這個名字將被賦值。因此,你總是看到B,因爲即使用new C,第一個C寫入C,然後A寫入A(覆蓋C),最後B寫入B(覆蓋A)。

如果你想在層級與每個級別的代碼有自己的name財產,你不能隨便做,但你可以通過讓每一個使用它自己的財產接近(例如,nameAnameBnameC)。您可以通過使用方括號表示法和每個級別的所有代碼共享的變量來以不需要記住哪個級別編寫代碼的方式來執行此操作。我不是推薦那個。無論您想要解決的實際問題是什麼,都可能有更好的解決方案。

但在這裏,你會怎麼做:

var A = (function() { 
 
    var name = "nameA"; // <== We declare a variable and put this level's property name in it 
 

 
    function A() { 
 
     this[name] = "A"; // <== Note we're using brackets notation here 
 
    } 
 

 
    A.prototype.a = function() { 
 
     snippet.log("this is a"+this[name]); // <== Brackets again here 
 
    }; 
 

 
    return A; 
 
})(); 
 

 
var B = (function() { 
 
    var name = "nameB"; // <== Same again for B 
 

 
    function B() { 
 
     this[name] = "B"; 
 
    } 
 

 
    B.prototype.b = function() { 
 
     snippet.log("this is b"+this[name]); 
 
    }; 
 

 
    return B; 
 
})(); 
 

 
var C = (function() { 
 
    var name = "nameC"; 
 

 
    function C() { 
 
     this[name] = "C"; 
 

 
     A.call(this); 
 
     B.call(this); 
 
    } 
 

 
    C.prototype = Object.assign({}, A.prototype, B.prototype); 
 
    C.prototype.constructor = C; 
 

 
    C.prototype.c = function() { 
 
     snippet.log("this is c"+this[name]); 
 
    }; 
 

 
    return C; 
 
})(); 
 

 
var x = new C(); 
 

 
x.a(); //this is aA 
 
x.b(); //this is bB 
 
x.c(); //this is cC
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

的一個對象的所有三個構造帶將結束三個屬性工作:nameAnameBnameC

同樣,我不推薦這麼做,只是指出它是可能的,並且可以適應一些問題,儘管目前還不清楚它是否適合您的問題。