简体   繁体   English

无法从父类继承构造函数

[英]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 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 http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

Because Cat doesn't accept an argument. 因为Cat不接受论点。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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