无法从父类继承构造函数

时间:2011-09-22 18:46:46

标签: javascript oop

我对构造函数的继承有问题:

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);

警告显示未定义。我做错了什么? jsfiddle

2 个答案:

答案 0 :(得分:3)

看起来你想要自动调用父构造函数,没有一些额外的工作就不支持。您的代码应如下所示

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);

如果使用库来实现继承,则不必担心这一点。如果您不想创建空构造函数,它们甚至可以自动调用您的父构造函数。上面的代码仍然不理想。看到我写的一篇文章谈到了继承的“正确”方式。 http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

答案 1 :(得分:0)

因为Cat不接受争论。这就是你想要的:

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);