【问题标题】:How to call base class methods in typescript如何在打字稿中调用基类方法
【发布时间】:2019-04-16 22:36:43
【问题描述】:

我希望它调用 Animal 类方法,而不是 Snake。

当我进行强制转换时实际发生了什么? 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()

编辑: 固定输出 输出:

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

在这种情况下,我不必打印 My name is ssssamy and I'm an animal? 我认为重载方法,应该调用base中的方法,因为我在snake中使用了强制转换。

【问题讨论】:

    标签: typescript inheritance this super


    【解决方案1】:

    这在 JS 中并不是一件很自然的事情。从概念上讲,一切都是virtual。我所知道的没有与 C# 的 new 隐藏覆盖类似的等效项。 JS 使用原型进行继承。此处介绍的内容太多,但您可以在本文中了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

    我能想到的一种方法是......

    Animal.prototype.toString.call(sammy);
    

    这应该导致:

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

    【讨论】:

    • 您的回答与TS无关,在JS中,请阅读完整问题。
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2015-08-29
    • 2016-02-18
    • 2019-11-02
    • 1970-01-01
    • 2019-08-25
    • 2019-11-15
    • 2018-07-01
    相关资源
    最近更新 更多