javascript - 为什么我在原型(prototype)中定义时无法调用函数?

标签 javascript jquery inheritance

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

相关文章:

javascript - 如何将公历和伊斯兰历合二为一 (javascript)

Java编译器错误: "cannot find symbol constructor .."?

c# - C# 控制台应用程序之间的共享功能

javascript - 使用模式表单 ajax 的 HTMLFormElement.toString 超出了最大调用堆栈大小

javascript - 滚动后更改标题的容器

c# - 如何限制子类在 C# 中覆盖父类方法?

javascript - 如何使用reactJS 创建过滤搜索表。尝试让我的搜索栏过滤表中的信息

javascript - jQuery append() 在开头添加

javascript - 如何更改 ViewerJS 上 View 的默认大小

javascript - 如何停止 HTML 表单域中的文本突出显示