Typescript中的子类化 [英] Subclassing in Typescript

查看:80
本文介绍了Typescript中的子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Typescript中有一个存储类,该存储类实现了Storage接口,例如MyStorage.但是它有太多方法,所以我想用它代替MyStorage.getCandy-MyStorage.Candies.getCandies. 结构看起来如何?

I have a storage class in Typescript, that implements Storage interface, say MyStorage. But it has too many methods, so I want to use it instead of MyStorage.getCandy - MyStorage.Candies.getCandies. How can the structure possibly look?

我认为,类似

export class MyStorage implements Storage {

public constructor {} ...

Candies: {
   getCandies() { ... }
}

Balls: {
...
}
}

推荐答案

您应该考虑这样一个巨大的对象是否有意义.做所有事情的类通常不是一个好主意,您应该将它们分成几个类,每个类都处理特定的对象类型(例如,一个用于Balls的类,一个用于Candies的类,等等),并使用这些类.如果要共享代码,可以将其放在基类中(如果没有具体功能,则最好是抽象基类).一个解决方案可能看起来像这样:

You should consider whether such a huge object makes sense. Classes that do everything are generally a bad idea, you should split them up in several classes that each deals with a specific object type (ie one class for Balls, one for Candies etc.) and use those classes. If you want to share code you can put it in a base class (preferably an abstract base class if it has no concrete functionality). A solution might look like this:

export abstract class MyStorage implements Storage { 

}
export class CandiesStorage extends MyStorage { 
    getCandies() {}
}

export class BallsStorage extends MyStorage { 
}

话虽如此,如果由于您自己的原因这是不可行的,则可以拆分这样的功能,只是操作符错误,您需要使用=而不是Candies字段>(:是类型注释,而不是类内部的字段初始化).这种方法的一个问题是,如果使用常规函数,则在对象文字函数(例如getCandies)中,this将引用对象文字.最简单的解决方案是使用箭头功能或添加额外的owner字段以允许访问包含的类实例.这是说明这两种选择的解决方案:

That being said, if for your own reasons this is not feasible, you can split up the functions like this, you just have the operator wrong, you need to initialize the Candies field with = not with : (: is a type annotation not field initialization inside a class). One problem with this approach is that inside the object literal functions (for example getCandies), this will refer to the object literal if you use regular functions. The simplest solution would be to use an arrow function or to add an extra owner field to allow access to the containing class instance. Here is a solution that exemplifies both options:

export class MyStorage implements Storage {

    public constructor (){ }

    Candies = {
        getCandies: () => {
            this.Balls // this refers to MyStorage
        }
    }

    Balls = { 
        owner: this, // capture the owner object in a field
        getBalls() {
            this.owner.Candies // this refers to the Balls objects, but we can use owner to access the container
        }
    }
} 

这篇关于Typescript中的子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆