我正在做一个继承的例子。我想访问 abc
和 pqr
的所有属性,因此我使用了 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());
最佳答案
问题是因为您在创建 getr()
后覆盖了 pqr.prototype
。交换这些语句的顺序:
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());
关于javascript - 为什么我在原型(prototype)中定义时无法调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41674015/