用于动物的基本JavaScript原型和继承示例

用于动物的基本JavaScript原型和继承示例,javascript,Javascript,我试图通过非常简单的例子来掌握JavaScript的OOP 我的目标是创建一个以动物为例的类层次结构 在简化的动物等级体系中,我们可以看到如下内容: Animal /\ Mammal Reptile /\ /\ Human Dog Snake Alligator 我想以这个例子为例,在JavaScript中创建类。这是我的尝试。我能做些什么使它更好 function Animal(name) {

我试图通过非常简单的例子来掌握JavaScript的OOP

我的目标是创建一个以动物为例的类层次结构

在简化的动物等级体系中,我们可以看到如下内容:

          Animal
            /\
    Mammal     Reptile
      /\          /\
  Human Dog  Snake Alligator 
我想以这个例子为例,在JavaScript中创建类。这是我的尝试。我能做些什么使它更好

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

function Mammal() {
    this.hasHair = true;
    this.numEyes = 2;
    this.blood = "warm";
}

function Dog(breed) {
    this.breed = breed;
    this.numLegs = 4;
}

Dog.prototype = new Animal("Fido");
Dog.prototype = new Mammal();

var Fido = new Dog("Lab");

console.log(Fido.name); // returns undefined when i want it to return Fido
console.log(Fido.hasHair); // returns true as expected
console.log(Fido.breed); // returns lab as expected
我想做的是让狗扩展哺乳动物和动物的属性,因为两者都是,但它不能正常工作。我之所以这样假设是因为我在new Animal()之后调用dog.prototype=new demal(),它正在覆盖连接

如何正确写出这些类,以便调用它们父类的所有属性


谢谢。

您希望使用原型继承,这在Javascript中有点笨拙,但功能强大

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

// Example method on the Animal object
Animal.prototype.getName = function() {
    return this.name;
}

function Mammal(name, hasHair) {
    // Use the parent constructor and set the correct `this`
    Animal.call(this, name);

    this.hasHair = hasHair;
}

// Inherit the Animal prototype
Mammal.prototype = Object.create(Animal.prototype);

// Set the Mammal constructor to 'Mammal'
Mammal.prototype.constructor = Mammal;

Mammal.prototype.getHasHair = function() {
    return this.hasHair;
}

function Dog(name, breed) {
    // Use the parent constructor and set the correct `this`
    // Assume the dog has hair
    Mammal.call(this, name, true);

    this.breed = breed;
}

// Inherit the Mammal prototype
Dog.prototype = Object.create(Mammal.prototype);

// Set the Dog constructor to 'Dog'
Dog.prototype.constructor = Dog;

Dog.prototype.getBreed = function() {
    return this.breed;
}

var fido = new Dog('Fido', 'Lab');

fido.getName();  // 'Fido'
fido.getHasHair(); // true
fido.getBreed(); // 'Lab'

可以在

上找到一个很好的Javascript OOP资源,这大概就是您想要的吗?这太棒了!评论使其易于理解。我有几个后续问题:“emdama.prototype=Object.create(Animal.prototype);”这与“emdama.prototype=new Animal()”相同吗?根据我的基本知识,您创建了Animal类,但没有方法,并且单独创建了Animal.prototype.getName。这被认为是“良好实践”,因为它不会“污染”父类,每次创建新动物时都需要创建方法?对吗?我所理解的只是这是“良好的实践”,我不明白为什么会是这样。谢谢。首选使用Object.create,因为它基于给定的原型创建对象,而无需调用Animal构造函数。在定义遗传时,哺乳动物和狗并没有名字传给动物的构造器。像我一样在构造函数中调用父构造函数可以让您传递参数。你是对的。如果将方法设置为Animal类而不是其原型,则会为每个实例创建该函数的新副本。如果它在原型上,动物就不会有方法的副本,但它知道检查原型。