问题描述
在 JavaScript权威指南5版一书中,9.2节原型和继承,我找到以下字样:
现在,如果确实如此,原型继承如何存在?我的意思是,假设构造函数的原型对象最初具有构造函数属性。因为原型对象本身是一个对象,为了确定它的构造函数,我们经常使用 prototype_object.constructor
。但是现在 prototype_object
已经有一个构造函数
属性本身,它指向 构造函数与原型相关联的 。在这种情况下,如何存在继承?
让我们说,狗是一个哺乳动物。
function Mammal(){
this.milk = true;
};
function Dog(){
this.bark = true;
}
Dog.prototype =新的哺乳动物;
所以Dog points的原型到哺乳动物的对象。这个Mammal对象有一个对它的构造函数的引用,所以当Dog是新的时,JavaScript看到Dog原型是一个哺乳动物,所以调用Mammal的构造函数来生成一个有效的Mammal对象(另一个)然后使用Dog构造函数使它成为Dog对象。 p>
从这里, Dog.prototype
的构造函数是 Mammal
(添加了额外字段和函数的哺乳动物对象) Dog
的构造函数是 Dog
。遗传的存在是因为Dog的一个实例以哺乳动物为原型;因此,狗是一个哺乳动物。当一个方法被调用并且JS无法从 Dog.prototype
中找到它时,JS会查看 Mammal.prototype
(这是添加了额外字段和函数的Object。)
希望这会有所帮助。
In the book "JavaScript the definitive guide 5 edition", section 9.2 Prototypes and Inheritance, I find the following words:
Now, if that is true, how could prototypal inheritance exists? I mean, let's say the prototype object of a constructor function has a constructor property initially. Because the prototype object itself is an object, to determine its constructor we often use prototype_object.constructor
. But now the prototype_object
already has a constructor
property itself, and it points to the constructor function with which the prototype is associated. In this situation how can inheritance exists?
Let say, Dog is a Mammal.
function Mammal() {
this.milk = true;
};
function Dog() {
this.bark = true;
}
Dog.prototype = new Mammal;
So prototype of Dog points to an object of Mammal. This Mammal object has a reference to its constructor so when Dog is new, JavaScript see that Dog prototype is a Mammal so Mammal's constructor is called to produce a valid Mammal object (another one) then make it a Dog object using Dog constructor.
From this, the constructor of Dog.prototype
is a Mammal
(a Mammal Object that has extra fields and functions added) BUT constructor of Dog
is Dog
. The inheritance exist because the an instance of Dog has a Mammal as a prototype; hence, Dog is a Mammal. When a method is called and JS cannot find it from Dog.prototype
, JS look in Mammal.prototype
(which is an Object that has extra fields and functions added).
Hope this helps.
这篇关于对JavaScript原型继承感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!