首页 > 解决方案 > 在 Typescript 中销毁类成员变量

问题描述

我有一个用打字稿写的类,在某些时候我想清除类成员变量。我怎么能在打字稿中做到这一点。

export Class Example{ 
 storeNames: [] = [];
 storeAddress: [] = [];

constructor(){
    this.storeNames = ['mike','nelson'];
    this.storeAddress = ['US','UK'];
}

clearData(){
//here i want to clear those variables, but not in old fashion way,
//I meant assigning them again empty array (this i don't want, because if there are 10 variables then i have to clear them in this method, which is more inefficient way (i feel)
}

}

标签: typescript

解决方案


这里并没有真正的魔法,你只是做你说你不想做的事,给他们分配新的价值。最简单和最清晰的方法是只使用无聊的旧作业:

this.storeNames = [];
this.storesAddress = [];
// ...

您可以使用循环结构和动态属性名称访问,但不太清楚:

for (const name of ["storeNames", "storeAddress"]) {
    this[name] = [];
}

旁注:您的属性名称storeNamesstoreAddress建议您将数据存储在并行数组中(storeNames[0]是商店的名称storeAddress[0]等)。一般来说,这不是最佳做法。相反,存储一个存储对象数组:

export class Example {

    stores: Store[] = [];

    constructor() {
        this.stores = [
            new Store("mike", "US"),
            new Store("nelson", "UK")
        ];
    }

    clearData() {
        this.stores = [];
    }

}

这还具有通过单个分配清除整个商店的优点。


推荐阅读