简体   繁体   中英

javascript prototype throw the error as “Object [object Object] has no method”

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM