对JavaScript原型继承感到困惑
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了对JavaScript原型继承感到困惑,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1911字,纯文字阅读大概需要3分钟。
内容图文
![对JavaScript原型继承感到困惑](/upload/InfoBanner/zyjiaocheng/766/1471114e819746c581c92978dbe24bb6.jpg)
在“JavaScript权威指南5版”,第9.2节“原型和继承”一书中,我找到了以下几个字:
In the previous section, I showed that
the new operator creates a new, empty
object and then invokes a constructor
function as a method of that object.
This is not the complete story,
however. After creating the empty
object, new sets the prototype of that
object. The prototype of an object is
the value of the prototype property of
its constructor function. All
functions have a prototype property
that is automatically created and
initialized when the function is
defined. The initial value of the
prototype property is an object with a
single property. This property is
named constructor and refers back to
the constructor function with which
the prototype is associated. (You
may recall the constructor property
from Chapter 7 ; this is why every
object has a constructor property.)
Any properties you add to this
prototype object will appear to be
properties of objects initialized by
the constructor.
现在,如果这是真的,那么原型继承如何存在?我的意思是,假设构造函数的原型对象最初具有构造函数属性.因为原型对象本身就是一个对象,为了确定它的构造函数,我们经常使用prototype_object.constructor.但是现在prototype_object本身已经有了一个构造函数属性,它指向与原型相关联的构造函数.在这种情况下,如何存在继承?
解决方法:
比方说,狗是一个哺乳动物.
function Mammal() {
this.milk = true;
};
function Dog() {
this.bark = true;
}
Dog.prototype = new Mammal;
所以狗的原型指向哺乳动物的对象.这个Mammal对象有一个对它的构造函数的引用,所以当Dog是新的时,JavaScript看到Dog原型是一个哺乳动物,所以调用Mammal的构造函数来生成一个有效的Mammal对象(另一个)然后使用Dog构造函数使它成为Dog对象.
由此,Dog.prototype的构造函数是一个哺乳动物(一个哺乳动物对象,其中添加了额外的字段和函数)但是Dog的构造函数是Dog.遗传的存在是因为Dog的一个实例以哺乳动物为原型;因此,狗是一个哺乳动物.当调用方法并且JS无法从Dog.prototype中找到它时,JS会查看Mammal.prototype(这是一个添加了额外字段和函数的Object).
希望这可以帮助.
内容总结
以上是互联网集市为您收集整理的对JavaScript原型继承感到困惑全部内容,希望文章能够帮你解决对JavaScript原型继承感到困惑所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。