我正在进行原型继承方法测试..我收到错误,即使我将实例复制到现有对象...
这里有什么问题..
我的测试:
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"
这里有什么问题..谁帮我理解我的错误?
答案 0 :(得分:1)
你需要说
var male = function(gender){
this.gender = gender;
}
male.prototype = new human();
不要忘记您还需要设置男性对象的name
属性。您可以在setName
上公开human
方法,并在male
构造函数中调用该方法。
答案 1 :(得分:0)
prototype属性仅在构造函数/函数上定义。所以......
var obj = { a: 10 };
obj.prototype = { b : 20 }; // Wont't work
obj.constructor.prototype.say = function(){
alert("Hello");
}
obj.say(); // Works.
我希望你明白