0

I am doing a prototype inheritance method test.. i am getting a error, even after i copied the instance to my existing object...

what is wrong here..

my test :

var human = function(name){
    this.name = name;
}

human.prototype.say = function(){
    alert(this.name);
}

var male = function(gender){
    this.gender = gender;
}

male.prototype.Gender = function(){
    alert(this.gender);
}

var inst1 = new human('nw louies');
inst1.say();

var inst2 = new male("male");
inst2.prototype = new human("sa loues philippe"); //i am copying the instance of human
inst2.Gender();
inst2.say(); // throw the error as "undefined"

what is wrong here.. any one help me to understand my mistake?

live demo here

2 Answers 2

1

You need to say

var male = function(gender){
    this.gender = gender;
}

male.prototype = new human();

Don't forget that you also need to set the name property of male objects. You could expose a setName method on human and call that in the male constructor function, for example.

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

2 Comments

can you please update my jsfiddle to get more understanding please?
Have a look at this: jsfiddle.net/4WDxR/2 I hope it is of some help for your, feel free to ask otherwise
0

The prototype property is defined on constructors/functions only. So...

var obj = { a: 10 };
obj.prototype = { b : 20 }; // Wont't work

obj.constructor.prototype.say = function(){
    alert("Hello");
}

obj.say(); // Works.

I hope you understand

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.