Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 容器对象的引用相等_Javascript_Typescript - Fatal编程技术网

Javascript 容器对象的引用相等

Javascript 容器对象的引用相等,javascript,typescript,Javascript,Typescript,对于特定的应用程序,我们将对象的id存储在特定的类中。例如,“product”对象将其字符串id存储在“ProductId”对象中。同样,“user”对象将其字符串id存储在UserId对象中(参见下面的示例代码) 这种方法的一个问题是,将对象存储在映射中,然后尝试检索它们(请参见下面的代码)不起作用,因为具有相同基础id的两个用户id与==不相等 const users = new Map<UserId, User>(); const user = new User(new Us

对于特定的应用程序,我们将对象的id存储在特定的类中。例如,“product”对象将其字符串id存储在“ProductId”对象中。同样,“user”对象将其字符串id存储在UserId对象中(参见下面的示例代码)

这种方法的一个问题是,将对象存储在映射中,然后尝试检索它们(请参见下面的代码)不起作用,因为具有相同基础id的两个用户id与==不相等

const users = new Map<UserId, User>();

const user = new User(new UserId('8753098'), 'John'); 
users.set(user.id, user);

console.log(users.get(new UserId('8753098')); //undefined
const users=newmap();
const user=new user(new UserId('8753098'),'John');
users.set(user.id,user);
console.log(users.get(新用户ID('8753098'));//未定义
javascript似乎没有运算符重载,或者没有方法重写相等函数

我还考虑过使用全局映射,并使用静态方法创建Id:

class UserId {

  private id: string;

  constructor(id: string) {
    this.id = id;
  }

  static userIds = new Map<string, UserId>();    

  static fromString(id: string) {
    let userId = userIds.get(id);
    if (userId === undefined) {
      userId = new UserId(id);
      userIds.set(id, userId);
    }
    return userId;
  }
}
类用户ID{
私有id:string;
构造函数(id:string){
this.id=id;
}
静态userid=newmap();
静态fromString(id:string){
让userId=userIds.get(id);
if(userId==未定义){
userId=新的userId(id);
userId.set(id,userId);
}
返回用户标识;
}
}
但这有一个潜在的内存泄漏,因为所有对象都保留在地图中,永远不会释放

有人能解决这个问题吗

有人能解决这个问题吗

只需执行一个type
type UserId=string
,而不是
class UserId

更多 如果您关心结构的平等性,并且希望使用命名类型,那么可以使用枚举添加一个品牌

有人能解决这个问题吗

只需执行一个type
type UserId=string
,而不是
class UserId

更多 如果您关心结构的平等性,并且希望使用命名类型,那么可以使用枚举添加一个品牌


我不确定这是否符合您的目的,但也可以在
UserId
类中设置
toString()
。然后您可以通过
users.set(user.id.toString(),user)获取/设置;
我不确定这是否符合您的目的,但也可以在
UserId
类中设置
toString()
。然后您可以通过
users.set获取/设置(user.id.toString(),user);
非常有趣的文章非常有趣的文章
class UserId {

  private id: string;

  constructor(id: string) {
    this.id = id;
  }

  static userIds = new Map<string, UserId>();    

  static fromString(id: string) {
    let userId = userIds.get(id);
    if (userId === undefined) {
      userId = new UserId(id);
      userIds.set(id, userId);
    }
    return userId;
  }
}
enum UserIdBrand {}
type UserId = UserIdBrand & string;