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

sjm*_*tin 11 javascript

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

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

在简化的动物层次结构中,我们可能会看到如下内容:

          Animal
            /\
    Mammal     Reptile
      /\          /\
  Human Dog  Snake Alligator 
Run Code Online (Sandbox Code Playgroud)

我想采用这个例子并在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
Run Code Online (Sandbox Code Playgroud)

我想做的是让狗扩展哺乳动物和动物的属性,因为它是两者但它不能正常工作.我假设因为我正在调用dog.prototype = new Mammal()之后新的Animal()它正在覆盖连接.

如何正确写出这些类,以便我可以调用其父类的所有属性?

谢谢.

小智 7

你想利用原型继承,它在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'
Run Code Online (Sandbox Code Playgroud)

可以在Mozilla Developer Network上找到Javascript中OOP的良好资源