0

我正在做一个原型继承方法测试..我得到一个错误,即使我将实例复制到我现有的对象之后......

这里有什么问题..

我的测试:

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"

这里有什么问题..有人帮我理解我的错误吗?

现场演示在这里

4

2 回答 2

1

你需要说

var male = function(gender){
    this.gender = gender;
}

male.prototype = new human();

别忘了还需要设置name男性对象的属性。例如,您可以公开一个setName方法并在构造函数human中调用它。male

于 2013-07-25T12:15:14.870 回答
0

原型属性仅在构造函数/函数上定义。所以...

var obj = { a: 10 };
obj.prototype = { b : 20 }; // Wont't work

obj.constructor.prototype.say = function(){
    alert("Hello");
}

obj.say(); // Works.

我希望你明白

于 2013-07-25T12:17:21.260 回答