My question is about a strange output that I came across while playing with JS prototypal inheritance.
Please take a look:
function Parent(){
}
Parent.prototype = {
variable : 'a'
};
function Child(){
}
Child.prototype = new Parent();
child = new Child();
Parent.prototype =
{
variable : 'c'
};
console.log(child.variable); // output a
console.log(child.__proto__); // [object Object] { variable: 'a'}
Why the child did not inherit property?
Of course if I would do this this way:
function Parent(){
}
Parent.prototype.variable = 'a';
function Child(){
}
Child.prototype = new Parent();
child = new Child();
Parent.prototype.variable = 'c';
console.log(child.variable); // "c"
console.log(child.__proto__); // [object Object] { variable: "c"}
The output is expected: "c" and
[object Object] { variable: "c" }
does anyone know why the object 'prototype' is not beeing inherited while a normal property of 'prototype' is?