从另一个构造函数继承会覆盖继承的构造函数的原型链中的现有属性
does inheriting from another constructor overridedes the existing properties from the prototype chain of the constructor that inherits
这里有两个构造函数,比如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);
相关文章:
- 如何检查DOM节点是否继承自构造函数
- Javascript:继承原型而不重新定义构造函数
- 从类构造函数继承javascript
- JavaScript-构造函数参数和原型继承
- Javascript继承构造函数
- JavaScript继承构造函数.prototype
- 通过父构造函数创建主干继承视图
- JavaScript - 构造函数中的继承
- 构造函数原型-继承混淆
- Crockford 伪经典继承部分中的函数构造函数
- 通过构造函数属性和运算符实例设置继承
- 如何从“构造函数返回另一个对象”对象继承
- 从原型继承与从构造函数继承
- 继承和 TypeScript 错误:X 不是构造函数类型
- 命名空间和继承:具有JavaScript责任链的超级构造函数
- 我可以在 JavaScript 中模拟继承,只调用一个基构造函数,而不是使用原型吗?
- 继承:构造函数不运行'
- TypeScript类继承构造函数混淆
- Javascript继承构造函数
- 不能从父类继承构造函数