2017-01-16 96 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());

相关问题