2017-01-16 61 views
2

我正在做一個繼承的例子。我想訪問abcpqr的所有屬性,所以我用Object.create。但是,在調用getr()函數時,我無法獲得r的值。我究竟做錯了什麼?爲什麼我在定義原型時無法調用函數?

function abc() { 
 
    this.a = 3; 
 
} 
 
abc.prototype.getA = function() { 
 
    return this.a 
 
} 
 

 
function pqr() { 
 
    abc.call(this); 
 
    this.r = 3; 
 
} 
 
pqr.prototype.getr = function() { 
 
    return this.r 
 
} 
 
pqr.prototype = Object.create(abc.prototype); 
 

 
var n = new pqr(); 
 
console.log(n.getr());

+0

您連接'GETR()'來pqr'的'原型,然後_overwrite_是原型,因此爲什麼它不工作。 – vlaz

回答

2

的問題是因爲您覆蓋後pqr.prototype創建getr()。 SWAP這些語句的順序:

function abc() { 
 
    this.a = 3; 
 
} 
 
abc.prototype.getA = function() { 
 
    return this.a; 
 
} 
 

 
function pqr() { 
 
    abc.call(this); 
 
    this.r = 3; 
 
} 
 
pqr.prototype = Object.create(abc.prototype); 
 
pqr.prototype.getr = function() { 
 
    return this.r; 
 
} 
 

 
var n = new pqr(); 
 
console.log(n.getr());

相關問題