【问题标题】:JavaScript inheritance rulesJavaScript 继承规则
【发布时间】:2014-08-13 04:03:57
【问题描述】:

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

企鹅是动物的子类。

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

Penguin 构造函数只接受 1 个参数 name,而 Animal 构造函数接受 3 个参数:name、food 和 numLegs。

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

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

【问题讨论】:

    标签: javascript inheritance


    【解决方案1】:

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

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

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

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

    这是一种方法,其中Penguin 构造函数调用Animal 构造函数并传递numLegsfood 的参数,因为它们已知为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();
    

    仅供参考,设置原型的更现代方式是:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多