已解决
在最底部分配原型(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/