Can't inherit constructor from parent class
I have problem with inheritance of consturctor:
function Alive(name) {
this.name = name;开发者_C百科
}
var Cat = new Function();
Cat.prototype = new Alive();
Cat.prototype.constructor = Alive;
var cat = new Cat('Thomas');
alert(cat.name);
alert show undefined. What i do wrong? jsfiddle
Looks like you want the parent constructor to get called automatically, that's not supported without some extra work. Your code should look like the following
function Alive(name) {
this.name = name;
}
function Cat(name) {
// Call the parent constructor
Alive.call(this, name);
}
Cat.prototype = new Alive();
// This line is to fix the constructor which was
// erroneously set to Alive in the line above
Cat.prototype.constructor = Cat;
var cat = new Cat('Thomas');
alert(cat.name);
If you use a library to implement inheritance, you don't have to worry about this. They can even call your parent constructor automatically if you don't want to create an empty constructor. The above code is still not ideal. See a post I wrote that talks about the 'right' way to do inheritance. http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
Because Cat doesn't accept an argument. Here's what you want:
function Alive(name) {
this.name = name;
}
function Cat(name) {
Alive.call(this, name);
}
// since there's nothing on the prototype, this isn't necessary.
// Cat.prototype = new Alive();
var cat = new Cat('Tomas');
alert(cat.name);
精彩评论