JavaScript继承规则

标签 javascript inheritance

在codecademy学习JS,对第18/30课有关继承的一些技术细节感到困惑。

企鹅是动物的子类。

我将 Penguin 的原型(prototype)设置为 Animal,并在 Penguin 构造函数中指定了它的 numLegs。但是,我没有指定它的名称和食物,它们是 Animal 类的属性。

Penguin 构造函数仅采用 1 个参数(名称),而 Animal 构造函数采用 3 个参数:名称、食物和 numLegs。

例如,如果我创建一个名为“Bob”的新企鹅对象,它的 numLegs 和食物会是什么?

// the original Animal class and sayName method

function Animal(name, numLegs, food) {
    this.name = name;
    this.numLegs = numLegs;
    this.food = food;

}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin(name)
{
    this.numLegs=2;
    this.name=name;
}

// set its prototype to be a new instance of Animal
Penguin.prototype=new Animal();

最佳答案

food 是一个属性,当调用 Animal() 构造函数并传递三个参数时,该属性会在该构造函数中初始化。由于您永远不会使用这些参数以这种方式调用构造函数,并且永远不会在 Penguin 构造函数中设置 food 属性,因此该属性将是 undefined(从不设置)。

numLegs 属性的值为 2,因为您的 Penguin 构造函数始终将其设置为 2

name 属性将被设置,因为您是在 Penguin 构造函数中设置它。这里只有一个物体。对象中并不存在 Penguin 部分和 Animal 部分。只有一个对象和一组属性。无论属性在哪里设置(哪个构造函数或哪个方法),一旦设置,它就会设置在对象上。

继承的常用方法是为 Penguin 创建一个构造函数,其中包含初始化对象所需的所有属性(或子类自己手动设置一些参数),然后在 >Penguin 构造函数,您调用基础对象的构造函数并向其传递所需的参数。

这是一种方法,其中 Penguin 构造函数调用 Animal 构造函数并传递 numLegs 的参数food 因为它们已经为 Penguin 所知,因此不需要通过 Penguin 构造函数传入。

function Animal(name, numLegs, food) {
    this.name = name;
    this.numLegs = numLegs;
    this.food = food;
}

Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin(name) {
    // call parent constructor with this object and all three args it wants
    // so all the object properties get initialized appropriately
    Animal.call(this, name, 2, "fish");
}

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();
<小时/>

仅供引用,设置原型(prototype)的更现代的方法是:

Penguin.prototype = Object.create(Animal.prototype);

这避免了构造函数的任何副作用,并且只复制所需的原型(prototype)。 Object.create() 需要 IE9 或简单的 polyfill。

关于JavaScript继承规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25277838/

相关文章:

javascript - 条件关闭标签 ReactJS

javascript - Sencha Touch 和 Cookie

javascript - Reactjs 类与 javascript 类

c++ - 如何在不转换为派生类的情况下检查几何基类中的碰撞

javascript - 更改 jQuery Mobile 过渡方向

javascript - AngularJS JSON 范围

javascript - 我正在尝试将 HTML 表中的一行调用到 JS 函数中

inheritance - Kotlin:类继承了包含伴随对象的接口(interface),但无权访问接口(interface)的常量

c++ - 我还需要在子类方法上指定 virtual 吗?

c++ - 使用多态时如何避免向下转换?