Reputation: 15293
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?
Upvotes: 0
Views: 1138
Reputation: 12305
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
Upvotes: 0
Reputation: 14455
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.
Upvotes: 1