[Ionic]JSON.parse后类对象方法丢失问题

现有一个类(typescript)如下:

export class User {
  username: string;
  password: string;
  expired: boolean;

  isExpired() {
    return this.expired;
  }
}

假如我们这样来使用一下:

const a = new User();
a.isExpired();
const b = JSON.parse(JSON.stringify(a)) as User;
b.isExpired();

你会发现浏览器会报错:

b.isExpired is not a function

这是由于JSON.parse的转换不会将function也进行转换,只是将JSON string转换成了JSON object而已。需要进行如下多一步骤才能设置该object的原型prototype:

// const b = JSON.parse(JSON.stringify(a)) as User;
const c = new User();
Object.assign(c, b);
c.isExpired();
发布了372 篇原创文章 · 获赞 1031 · 访问量 242万+

猜你喜欢

转载自blog.csdn.net/moxiaomomo/article/details/103020936