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'}
5
  • 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. Commented Sep 12, 2014 at 16:05
  • It's inheriting the prototype. Not the constructor. Commented Sep 12, 2014 at 16:06
  • Yes your right. I'll edit my question. Why does it not inherit the values of the properties. Commented Sep 12, 2014 at 16:06
  • As I said: "Boy doesn't do anything with the arguments you provided." The function is empty. Commented Sep 12, 2014 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 Commented Sep 12, 2014 at 16:08

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.