[英]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.