Problem using the prototype chain
If I have a constructor that takes a number of arguments:
var Mammal = function(name, weight) {
this.name = name;
this.weight = weight;
}
Mammal.prototype.makeSound = function(sound) {
alert(sound);
}
Mammal.prototype.getName = function() {
return this.name;
}
and I want to do some inheritence:
var Human = function(name,weight,language,location) {
//code
}
Human.prototype = new Mammal();
In the last line here isn't the Human prototype getting assigned undefined for the name and weight parameters? I see this code all the time....I know that the Human constructor is being fed the name and weight params but it seems messy that the prototype is getting these undefined values. I know this only works because javascript is slack enough to allow you to do this. Is the开发者_C百科re a way to get round this?
What bothers you exactly?
Human.prototype = new Mammal();
alert( Human.prototype.name ); // undefined
alert( Human.prototype.foo ); // undefined
You can consider them as not being there. The reason why you're not writing:
Human.prototype = Mammal.prototype;
Is because the Mammal
constructor can add methods that are not on the prototype object.
var Mammal = function(name, weight) {
this.name = name;
this.weight = weight;
this.somefun = function() {
// this can't be inhereted by
// Mammal.prototype
}
}
In order not to reapeat yourself you can use Constructor Chaining:
var Human = function(name,weight,language,location) {
this.language = language;
this.location = location;
// call parent constructor
Mammal.apply(this, arguments);
}
This seems to be more straightforward, isn't it? You call the parent constructor to deal with the name
and weight
parameters, and you only care about Human
specific things in the Human
constructor.
i think i've seen something like this once:
var Human = function(name,weight,language,location) {
Mammal.call(this, name, weight);//calls the parent constructor
this.language = language;
this.lcoaiton = location;
}
Human.prototype = new Mammal();
精彩评论