How to call base class methods in typescript

时间:2019-04-16 22:36:43

标签: typescript inheritance this super

I expected it to call the Animal class method, not Snake.

What actually happens when I do a casting? typescript <Class>object


class Animal {
    name: string;
    constructor(theName: string) {
        this.name = theName;
        this.toString();
        console.log(`\tis Animal?: ${this instanceof Animal}`);
        console.log(`\tis Snake?:  ${this instanceof Snake}`);
        console.log(`\tis Horse?:  ${this instanceof Horse}`);
        console.log()
    }

    toString() {
        console.log(`My name is ${this.name} and I'm a animal`);
    }
}

class Snake extends Animal {
    name: string;

    constructor(nameAnimal: string, nameSnake: string) {
        super(nameAnimal);
        this.name = nameSnake;
    }

    toString() {
        console.log(`My name is ${this.name} and I'm a snake`);
    }
}

class Horse extends Animal {
    constructor(name: string) {
        super(name);
    }
}

// create my objects
let sammy = new Snake('Sammy the Python', 'sssssamy');
let tommy: Animal = new Horse('Tommy the Palomino');


// using method of snake
sammy.toString();

// casting 
const animal: Animal = (<Animal>sammy); // or const animal: Animal =  sammy as Animal;

// using method of animal
animal.toString()

EDIT: fixed output Output:

My name is Sammy the Python and I'm a snake
        is Animal?: true
        is Snake?:  true
        is Horse?:  false

My name is Tommy the Palomino and I'm a animal
        is Animal?: true
        is Snake?:  false
        is Horse?:  true

My name is sssssamy and I'm a snake 

My name is sssssamy and I'm a snake

In which case, I would not have to print My name is ssssamy and I'm an animal? I think overload method, and the methods in base should to be called, because I used the casting in snake.

1 个答案:

答案 0 :(得分:0)

It's not a very natural thing to do in JS. Conceptually everything is virtual so to speak. There is no equivalent I know of to something like C#'s new hiding overrides. JS uses prototypes for inheritance. It's too much to cover here but you can read more about it in this article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

One approach I can think of would be...

Animal.prototype.toString.call(sammy);

which should result in:

My name is Sammy the Python and I'm a animal