解决了
在最底层分配原型是覆盖了我以前的声明。感谢古法的快速回答。
我已经浏览了一下,找到了一个很好的答案,mods,如果这是一个傻瓜,我很抱歉。
密码..。我有三种功能,一、二和三。我希望三个从两个继承,两个从一个继承。三人的原型应该一直延伸到一个,而它就是这样做的。在三种情况下,我可以从一次调用方法。但是我不能从两个人那里调用方法。
下面是一个例子。
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时,我得到了“我活在一个类上”的预期输出。但是x.two还没有定义。当我查看原型链时,两条链上根本没有任何方法/属性。只有从一个原型是可访问的。
我的大脑在哭泣。
编辑--我还没有尝试过x.three,但它也没有定义。也许我继承的方式是覆盖原型而不是共享?虽然这是问题所在,但我觉得我可以接触到两个,而不是一个。我不知道为什么我可以访问根类,但两者之间没有,甚至在调用的实例上也没有。就好像三个只是一个参考。
发布于 2015-10-18 10:34:35
在向two和three添加方法之后,您将替换它们的原型。原型链可以正常工作,但是two和three方法在替换它们之后不在原型中。
在向原型添加方法之前替换它们:
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'
https://stackoverflow.com/questions/33196864
复制相似问题