JavaScript 继承:我的派生成员什么时候在哪里?
看一下下面的代码:
function Primate() {
this.prototype = Object;
this.prototype.hairy = true;
}
function Human() {
this.prototype = Primate;
}
new Human();
当您检查 new Human()
时,没有 hairy
成员。我希望会有一个。我是否有另一种方式可以从 Primate
继承?涉及 Object.create()
的东西(ECMAScript5 可以在我的场景中使用)?
Take a look at the following code:
function Primate() {
this.prototype = Object;
this.prototype.hairy = true;
}
function Human() {
this.prototype = Primate;
}
new Human();
When you inspect new Human()
, there's no hairy
member. I would expect there to be one. Is there another way I'm suppose to inherit from Primate
? Something involving Object.create()
(ECMAScript5 is fine to use in my scenario)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在编写代码时,使用
new Human()
创建的对象将具有一个名为prototype
的属性,其值是对Primate
函数的引用。这显然不是你想要的(而且也不是特别特别)。一些事情:
您通常想要修改旨在用作构造函数的函数的
原型
(使用new
操作员)。换句话说,您希望在Human
上设置prototype
(而不是在Human
的实例上)。< /p>您分配给
prototype
的值应该是所需类型的实例(或者,如果不需要初始化工作,则为所需类型的prototype< /code>),而不是对其构造函数的引用。
从来没有必要将
Object
(或Object
实例)显式分配给函数的原型
。这是隐式的。您可能想要更像这样的内容:
h
引用的Human
有一个名为hairy
的属性,其值为 true。在前面的示例中,仅在调用
Primate
时才为hairy
分配其值,这就是为什么Human.prototype
必须分配一个Human.prototype
的实例。代码>灵长类动物。可以这样写,这样就不需要这样的初始化。例子:
As your code is written, objects created using
new Human()
will have a property calledprototype
whose value is a reference to thePrimate
function. That's clearly not what you want (and it's not particularly special).A few things:
You usually want to modify the
prototype
of a function that's intended to be used as a constructor (with thenew
operator). In other words, you want to set theprototype
onHuman
(not on an instance ofHuman
).The value you assign to the
prototype
should be an instance of the desired type (or, if no initialization work is necessary, the desired type'sprototype
), not a reference to its constructor.It's never necessary to explicitly assign
Object
(orObject
instances) to a function'sprototype
. This is implicit.You probably want something more like this:
The
Human
referenced byh
has a property calledhairy
whose value is true.In the previous example,
hairy
is assigned its value only oncePrimate
is invoked, which is whyHuman.prototype
must be assigned an instance ofPrimate
. This could instead be written so that no such initialization is necessary.Example: