Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS prototype objects not inherited?

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?

like image 912
grzim Avatar asked Apr 17 '26 18:04

grzim


2 Answers

Why the child did not inherit property?

difference between re assigning and mutating

re assigning:

var org = {val:22};
var copy = org;
//re assigning org de references copy
//  before this line copy === org
//  but after this line it isn't
org = {val:44};
//what do you think the value of copy is
console.log(copy.val);//=22 re assigning org de references copy

mutating:

var org = {val:22};
var copy = org;
org.val=33;//mutating org
//mutating copy (copy.val=11) would affect org
//  because org and copy are still the same (copy === org)
console.log(copy.val);//=33 because mutated org

You should not create an instance of Parent to set the prototype of Child (use Object.create instead) and in your comments you set the prototype of Child to be Parent.prototype, you can't do that because a Child is a Parent but a Parent isn't a Child (for example: a Dog is an Animal but an Animal is not a Dog because Animal could be a Snake).

More on constructor functions and prototype can be found here: https://stackoverflow.com/a/16063711/1641941

like image 123
HMR Avatar answered Apr 20 '26 08:04

HMR


Child.prototype = new Parent(); will construct a new Parent-object with the current Parent.prototype object as Child.prototype.__proto__.

Using: Parent.prototype.variable = 'c'; will change the objects property variable, since it is still the same object as of Child.prototype.__proto__, the variable will be modified on Child too.

Since Parent.prototype = { variable: 'c' }; will change the Parent.prototype object, to a completely new object. But the reference of the old prototype (Child.prototype.__proto__ will still remain the old, there will be no modification.

like image 37
bbuecherl Avatar answered Apr 20 '26 09:04

bbuecherl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!