简体   繁体   中英

Can't inherit constructor from parent class

I have problem with inheritance of consturctor:

function Alive(name) {
   this.name = name;
}
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM