U
U
Umid2017-02-26 15:55:10
JavaScript
Umid, 2017-02-26 15:55:10

What does this piece of code give us?

class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}
 
class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}
 
class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
        console.log("Galloping...");
        super.move(distanceInMeters);
    }
}
 
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
 
sam.move();
tom.move(34);

Interested in the line:
let tom: Animal = new Horse("Tommy the Palomino");
tom: Animal what can it give us?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GTRxShock, 2017-02-26
@DarCKoder

Here you explicitly specify the superclass.
Moreover, you are not tied to a specific implementation, but use a kind of interface. So that later you can check the object for entry into the Animal set
https://learn.javascript.ru/instanceof
Next, in the code, you can check whether the object is an animal, a la:

if (tom instanceof Animal) { //do..(покормить/воды налить/спать уложить и тд }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question