typescript - 在 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)
}
}
解决方案
这里并没有真正的魔法,你只是做你说你不想做的事,给他们分配新的价值。最简单和最清晰的方法是只使用无聊的旧作业:
this.storeNames = [];
this.storesAddress = [];
// ...
您可以使用循环结构和动态属性名称访问,但不太清楚:
for (const name of ["storeNames", "storeAddress"]) {
this[name] = [];
}
旁注:您的属性名称storeNames
和storeAddress
建议您将数据存储在并行数组中(storeNames[0]
是商店的名称storeAddress[0]
等)。一般来说,这不是最佳做法。相反,存储一个存储对象数组:
export class Example {
stores: Store[] = [];
constructor() {
this.stores = [
new Store("mike", "US"),
new Store("nelson", "UK")
];
}
clearData() {
this.stores = [];
}
}
这还具有通过单个分配清除整个商店的优点。
推荐阅读
- powershell - 按计算机名/用户名过滤文件“yyyy-MM-dd_HH-mm-ss_Computername_Username_File.json”
- sql - 如何在没有 WITH 语法的情况下重写查询
- xamarin - Xamarin Camera2Basic 在照片上写入设备水印
- activiti - 无法实例化类 org.jeecg.modules.activiti.service.Impl.TaskFinishedLicenser
- c# - Azure 存储模拟器是否支持 blob 版本控制?如果是这样,我该如何启用它?
- apache-kafka - Kafka 协议:如何设置 max.poll.interval.ms
- android - 设备重启后,我的应用接收 BOOT_COMPLETED 广播比其他应用慢/晚?
- apache-spark - 如何计算考拉聚合中的唯一值
- node.js - 通过 URL 浏览时自动停止下载图像显示图像进入浏览器
- amazon-web-services - 在 ec2 公共 DNS 上启用 https