Reputation: 9066
Here i have two constructor say First and Second.
First inherits from Second.First also has a hair property on its prototype chain.
A newly created object say tom which supposed to be an instance of First constructor has also a user-defined property called nail.
If i want to log all the enumerable properties of tom object using a for...in loop it only shows name,nail and age.But hair property seems to be disappeared from its prototype chain.
Why hair property disappeared from the prototype chain?? How can i get it back??
<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>
Upvotes: 0
Views: 39
Reputation: 1547
You overrode the prototype
on
First.prototype=new Second();
make it
First.prototype.age=new Second().age;
and it works.
Upvotes: 2
Reputation: 14580
The problem is you set the hair
property on the default prototype for First
and then replace it with a new prototype, which means your original is lost. If you reorder the statements like this it will work:
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);
Upvotes: 1
Reputation: 125498
First.prototype.hair
is declared before
First.prototype
is overwritten with an instance of an object constructed by Second
when
First.prototype=new Second();
is called. To keep the hair
property added to the prototype of First
, add it to the prototype after you assign a instance of an object created by calling Second
i.e.
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);
}
Upvotes: 1