Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法从父类继承构造函数_Javascript_Oop - Fatal编程技术网

Javascript 无法从父类继承构造函数

Javascript 无法从父类继承构造函数,javascript,oop,Javascript,Oop,我对constructor的继承有问题: 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); 警报显示未定义。我做错了什么 看起来您希望自动调用父构造函数,如果不做一些额外的工作,这是不

我对constructor的继承有问题:

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

警报显示未定义。我做错了什么

看起来您希望自动调用父构造函数,如果不做一些额外的工作,这是不受支持的。您的代码应该如下所示

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

如果使用库来实现继承,则不必担心这一点。如果不想创建空构造函数,它们甚至可以自动调用父构造函数。上面的代码仍然不理想。请看我写的一篇文章,其中谈到了继承的“正确”方式

看起来您希望自动调用父构造函数,如果不做一些额外的工作,这是不受支持的。您的代码应该如下所示

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

如果使用库来实现继承,则不必担心这一点。如果不想创建空构造函数,它们甚至可以自动调用父构造函数。上面的代码仍然不理想。请看我写的一篇文章,其中谈到了继承的“正确”方式

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

因为猫不接受争论。以下是您想要的:

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

这个例子没有设置原型链,所以它不是继承。正如代码注释中提到的,没有理由设置它,因为没有任何东西可以继承。如果在原型上定义了任何内容,那就不同了。仍然需要设置原型链,否则cat instanceof Alive将返回false此示例不设置原型链,因此它不是继承。正如代码注释中所述,没有理由设置它,因为没有任何内容可继承。如果在原型上定义了任何内容,那就不同了。仍然需要设置原型链,否则cat instanceof Alive将返回false