[英]javascript prototype throw the error as “Object [object Object] has no method”
我正在做原型继承方法测试..即使将实例复制到现有对象中,我还是报错了。
这里怎么了..
我的测试:
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"
这是怎么了..有人帮助我理解我的错误吗?
你要说
var male = function(gender){
this.gender = gender;
}
male.prototype = new human();
不要忘记,您还需要设置雄性对象的name
属性。 例如,您可以向human
公开setName
方法,并在male
构造函数中调用它。
prototype属性仅在构造函数/函数上定义。 所以...
var obj = { a: 10 };
obj.prototype = { b : 20 }; // Wont't work
obj.constructor.prototype.say = function(){
alert("Hello");
}
obj.say(); // Works.
我希望你明白
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.