这里我有两个构造函数,即“First”和“Second”。
First继承自Second。First在其原型(prototype)链上也有一个hair属性。
一个新创建的对象,比如 Tom,它应该是 First 构造函数的实例,它还有一个名为nail的用户定义属性。
如果我想使用 for...in 循环记录 tom 对象的所有可枚举属性,它只显示姓名、指甲和年龄。但是头发属性似乎从其原型(prototype)链中消失了。
为什么头发属性从原型(prototype)链中消失了?我怎样才能把它找回来??
<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;
并且它有效。
关于javascript - 从另一个构造函数继承是否会覆盖继承构造函数的原型(prototype)链中的现有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831828/