2
解决JS原型链
分配在最底层的原型为重写我以前的声明。感谢Guffa的快速回答。
我一直在浏览和种类找到一个很好的答案,MODS,如果这是一个doop对不起。
向代码.. 我有三种功能,一个,两个,和三个分别。 我想三个从两个继承,两个从一个继承。三者的原型应该一路回到一个,它的确如此。 我可以从一个调用方法,而我在三个实例中。但我无法从两个方法调用方法。
下面是一个例子。
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,但它也是未定义的。也许我继承的方式是覆盖原型而不是共享? 虽然如果这是问题,我觉得我可以访问两个而不是一个。我不知道为什么我可以访问根类,但是不能访问根类,甚至不能访问被调用的实例。就好像三个只是一个参考。
为了上帝的爱,请不要使用document.write()的例子中。正是这些让w3school吸收太多的东西。我们主要摆脱它,不要把它带回来:P –
稀释是,这是有道理的。我基本上是在他们有机会看到日光之前擦除原型。而且有人可以访问,因为我从来没有重新分配它的原型。完美,非常感谢。 –