2

Why won't Javascript inherit the properties from a prototype

Example

function Man(name,age,color){
this.name = name;
this.age = age;
this.color = color;
}

boy = function Boy(){};

boy.prototype = new Man();

myboy = new boy('hari',14,'blue');

console.log(myboy); 
// => myboy {name:undefined, age:undefined, color:undefined}

It does not inherit the properties.

Its meant to have the properties

// => myboy {name:'hari', age:14, color:'blue'}
Le Fem
  • 99
  • 1
  • 11
  • 1
    *"It does not inherit the properties."* Uhm, yes it does, it clearly has `name`, `age` and `color`. They just don't have any values because you are calling `Man` without any arguments, and `Boy` doesn't do anything with the arguments you provided. – Felix Kling Sep 12 '14 at 16:05
  • It's inheriting the prototype. Not the constructor. – slebetman Sep 12 '14 at 16:06
  • Yes your right. I'll edit my question. Why does it not inherit the values of the properties. – Le Fem Sep 12 '14 at 16:06
  • As I said: *"`Boy` doesn't do anything with the arguments you provided."* The function is empty. – Felix Kling Sep 12 '14 at 16:07
  • Ok I understand. Can I inherit the constructor of Man? So I won't have to write the constructor every time I inherit a prototype – Le Fem Sep 12 '14 at 16:08

1 Answers1

4

It does not inherit the properties.

Yes it does, it clearly has name, age and color. They just don't have any values because you are calling Man without any arguments, and Boy doesn't do anything with the arguments you provided.

Your inheritance setup is simply incorrect. You should add the parent prototype to the prototype chain of the child using Object.create:

Boy.prototype = Object.create(
  Man.prototype,
  {constructor: {value: Boy, writable: true}}
);

And, like in other languages, you have to call the parent constructor inside the child constructor (applied to the new child instance), passing along all the needed argumants:

function Boy(name, age, color) {
  Man.call(this, name, age, color);
}
// or
function Boy() {
  Man.apply(this, arguments);
} 

More info:

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143