【问题标题】:why I am not able to call function while defining in prototype?为什么我在原型中定义时无法调用函数?
【发布时间】:2017-05-31 03:38:04
【问题描述】:

我正在做一个继承的例子。我想访问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());

【问题讨论】:

  • 您将getr() 附加到pqr 的原型上,然后覆盖 该原型,因此它不起作用。

标签: javascript jquery inheritance


【解决方案1】:

问题是因为您在创建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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多