javascript - JS原型(prototype)链

标签 javascript inheritance

已解决

在最底部分配原型(prototype)会覆盖我之前的声明。感谢 Guffa 的快速回答。


我一直在浏览并找到一个好的答案,mods,如果这是一个错误,我很抱歉。

到代码.. 我有三个函数,分别是一、二、三。 我希望三个继承两个,两个继承一个。三的原型(prototype)应该一直回到一,事实确实如此。 当我处于三个实例中时,我可以调用其中一个的方法。但我无法从两个调用方法。

这是一个例子。

function one () {
  this.version = 1;
};

one.prototype.one = function () {
  return 'I live on the one class';
};

function two () { // extends one
  this.version = 2;
};

two.prototype.two = function () {
  return 'I live on the two class';
};

function three () { // extends two
  this.version = 3;
};

three.prototype.three = function () {
  return 'I live on the three class';
};

two.prototype = Object.create(one.prototype);
three.prototype = Object.create(two.prototype);

var x = new three();

x.one // -> 'I live on the one class!'
x.two // -> undefined
x.three // -> undefined

当我调用 x.one 时,我得到了“i live on the one class”的预期输出。 但 x.two 未定义。 当我查看原型(prototype)链时,二元链上根本没有方法/属性。仅可访问其中的原型(prototype)。

我的大脑在哭泣。

编辑 我还没有尝试过 x. Three,但它也是未定义的。也许我继承的方式是覆盖原型(prototype)而不是共享? 尽管如果这是问题所在,我觉得我可以访问两个而不是一个。我不确定为什么我可以访问根类,但中间没有,甚至在被调用的实例上也没有。就好像 3 只是对 1 的引用。

最佳答案

在向 two Three 添加方法后,您将替换它们的原型(prototype)。原型(prototype)链工作正常,但替换后,two Three 方法不在原型(prototype)中。

在向原型(prototype)添加方法之前替换原型(prototype):

function one () {
  this.version = 1;
};

one.prototype.one = function () {
  return 'I live on the one class';
};

function two () { // extends one
  this.version = 2;
};

two.prototype = Object.create(one.prototype);

two.prototype.two = function () {
  return 'I live on the two class';
};

function three () { // extends two
  this.version = 3;
};

three.prototype = Object.create(two.prototype);

three.prototype.three = function () {
  return 'I live on the three class';
};

var x = new three();

// Show values in snippet
document.write(x.one() + '<br>'); // -> 'I live on the one class'
document.write(x.two() + '<br>'); // -> 'I live on the two class'

关于javascript - JS原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33196864/

相关文章:

c# - 如何使用 20 字节 key 进入 AES ECB 模式

C++ 模板类的自继承

c++ - 一个类可以有虚拟数据成员吗?

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

javascript - PDF 文档超链接 javascript 以更改父窗口 URI

javascript - jQuery 按钮不执行?

javascript - 如何在 Node.JS 中中止失败的 Q Promise

javascript - 即使在 main 中全局分配了 ipc, Electron 菜单仍然显示单击时未定义 ipc

c++ - 关于 C++ 上虚拟运算符 * 的问题

Python:在初始评估后向类添加父类