为什么你需要在继承期间重置JavaScript构造函数? [英] Why do you need to reset javascript constructor during inheritance?

查看:106
本文介绍了为什么你需要在继承期间重置JavaScript构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么重要的是我将构造函数从Mammal重置为Cat?我一直在玩这个代码,并没有发现任何负面影响的错误构造函数。

Why is it important that I reset the constructor from Mammal to Cat? I've been playing around with this code and haven't found any negative effects of having the "wrong" constructor.

function Mammal(name){
    this.name=name;
    this.offspring=[];
}

Cat.prototype = new Mammal();        // Here's where the inheritance occurs
Cat.prototype.constructor=Cat;       // Otherwise instances of Cat would have a constructor of Mammal

function Cat(name){
    this.name=name;
}

例如:

function Mammal(name){
    this.name=name;
    this.offspring=[];
}

Cat.prototype = new Mammal();        // Here's where the inheritance occurs


function Cat(name){
    this.name=name;
    this.hasFur = true;
}

c1 = new Cat();
alert(c1.hasFur); //returns true;


推荐答案

技术上你不需要这样做,但是因为你替换了整个 .prototype 对象,你失去了 .constructor 这是默认放在那里,所以如果你有依赖它的代码,你需要手动包括它。

Technically you don't need to do that, but since you're replacing the entire .prototype object, you're losing the .constructor that's put there by default, so if you have code that relies on it, you need to manually include it.

这篇关于为什么你需要在继承期间重置JavaScript构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆