首页
学习
活动
专区
圈层
工具
发布

JS原型链
EN

Stack Overflow用户
提问于 2015-10-18 10:28:09
回答 1查看 98关注 0票数 2

解决了

在最底层分配原型是覆盖了我以前的声明。感谢古法的快速回答。

我已经浏览了一下,找到了一个很好的答案,mods,如果这是一个傻瓜,我很抱歉。

密码..。我有三种功能,一、二和三。我希望三个从两个继承,两个从一个继承。三人的原型应该一直延伸到一个,而它就是这样做的。在三种情况下,我可以从一次调用方法。但是我不能从两个人那里调用方法。

下面是一个例子。

代码语言:javascript
复制
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,但它也没有定义。也许我继承的方式是覆盖原型而不是共享?虽然这是问题所在,但我觉得我可以接触到两个,而不是一个。我不知道为什么我可以访问根类,但两者之间没有,甚至在调用的实例上也没有。就好像三个只是一个参考。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-18 10:34:35

在向twothree添加方法之后,您将替换它们的原型。原型链可以正常工作,但是twothree方法在替换它们之后不在原型中。

在向原型添加方法之前替换它们:

代码语言:javascript
复制
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'

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33196864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档