简体   繁体   English

javascript原型抛出错误,因为“对象[object Object]没有方法”

[英]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. 不要忘记,您还需要设置雄性对象的name属性。 You could expose a setName method on human and call that in the male constructor function, for example. 例如,您可以向human公开setName方法,并在male构造函数中调用它。

The prototype property is defined on constructors/functions only. prototype属性仅在构造函数/函数上定义。 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 我希望你明白

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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