从另一个构造函数继承会覆盖继承的构造函数的原型链中的现有属性

does inheriting from another constructor overridedes the existing properties from the prototype chain of the constructor that inherits

本文关键字:继承 构造函数 属性 覆盖 另一个 原型      更新时间:2023-09-26

这里有两个构造函数,比如First和Second。

First继承自Second。First在其原型链上也有一个hair属性。

一个新创建的对象,比如tom,应该是First构造函数的一个实例,也有一个名为nail的用户定义属性。

如果我想使用for来记录tom对象的所有可枚举属性。。。在循环中,它只显示姓名、指甲和年龄。但头发的特性似乎从其原型链中消失了。

为什么头发的特性从原型链中消失了??我怎样才能把它拿回来??

<html>
<body>
<script>
   function First(name){
       this.name=name;
   }
   First.prototype.hair='black';// tom.hair gets me undefined
   function Second(){
       this.age=1;
   }
   First.prototype=new Second();
   var tom=new First('tom');
   tom.nail='sharp';// added property to tom
   for(var i in tom){
       console.log(i);
   }
   console.log(tom.hair);
</script>
</body>
</html>

您覆盖上的prototype

First.prototype=new Second();

使其成为

First.prototype.age=new Second().age;

它是有效的。

JSFIDDLE

First.prototype.hair 

在之前声明

First.prototype 

时用Second构建的对象的实例重写

First.prototype=new Second(); 

被调用。要将hair属性添加到First的原型中,请在分配通过调用Second(即)创建的对象的实例后将其添加到原型中

function First(name){
    this.name=name;
}
function Second(){
    this.age=1;
}
First.prototype=new Second();
// add to prototype after overwriting/assigning prototype above
First.prototype.hair='black';
var tom=new First('tom');
tom.nail='sharp';
for(var i in tom){
    console.log(i);
}

问题是在First的默认原型上设置hair属性,然后用新原型替换它,这意味着原始原型丢失了。如果你像这样重新排序语句,它会起作用:

function First(name){
    this.name=name;
}
function Second(){
    this.age=1;
}
First.prototype=new Second();
First.prototype.hair='black'; // this works now!
var tom=new First('tom');
tom.nail='sharp';// added property to tom
for(var i in tom){
    console.log(i);
}
console.log(tom.hair);