简体   繁体   English

将字符串转换为 object 并调用 function

[英]Convert a string to an object and call a function

I want to store an object as a string, and then convert ot back to an object and call a method of this object.我想将 object 存储为字符串,然后将 ot 转换回 object 并调用此 object 的方法。

    user.delete() // this works
    self.user = JSON.stringify(user)
    const storeUser = JSON.parse(self.user)
    storeUser.delete() // Error: delete is not a function

As has been said in comments, functions/methods are not part of the JSON format so they are not present when you serialize to JSON.正如评论中所说,函数/方法不是 JSON 格式的一部分,因此当您序列化为 JSON 时它们不存在。 Same with class names and such.与 class 名称等相同。 So, when you call JSON.stringify() , it does not include any information about what type of class it is or any of the methods associated with that object.因此,当您调用JSON.stringify()时,它不包含任何关于它是什么类型的 class 或与该 object 相关的任何方法的任何信息。 When you then call JSON.parse() , all you will get back is instance data in a plain object.然后,当您调用JSON.parse()时,您将得到的只是普通 object 中的实例数据。 That's just one of the limitations of JSON.这只是 JSON 的限制之一。

Normally, you will not serialize code like methods.通常,您不会像方法一样序列化代码。 Instead, you will serialize what type of object it is, serialize the relevant instance data and then you want to reinstantiate the object, you will look at the data to see what type of object it is, call the constructor to make an object of that type and pass to the constructor the data you serialized from the prior object and you will have built a version of the constructor that takes exactly the data you are serializing so it can properly initialize the new object. Instead, you will serialize what type of object it is, serialize the relevant instance data and then you want to reinstantiate the object, you will look at the data to see what type of object it is, call the constructor to make an object of that键入并将您从之前的 object 序列化的数据传递给构造函数,您将构建一个构造函数版本,该版本完全采用您正在序列化的数据,因此它可以正确初始化新的 object。

If JSON.parse and JSON.stringify would allow a copy of methods, your code would be insecure and would have risks of people running arbitrary code on your server/computer since normally JSON string comes from external sources.如果JSON.parseJSON.stringify允许复制方法,那么您的代码将是不安全的,并且会有人们在您的服务器/计算机上运行任意代码的风险,因为通常 Z0ECD11C1D7A287401D148A23BBD7 来自外部字符串。

You should allow your User's class to parse a json and create a new instance based on that json:您应该允许您的用户的 class 解析 json 并基于该 json 创建一个新实例:

class User {
  constructor(someRandomProperty) {
    // ... code
  }

  static fromJson(userJson) {
    let props;
    try {
      props = JSON.parse(userJson);
    } catch (error) {
      throw new Error("Invalid Json User");
    }

    return new User(props.name, props.someRandomProperty);
  }

  delete() {
    // .... code
  }
}

And then you would copy the user like this:然后你会像这样复制用户:

User.fromJson(yourJsonStrinHere)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM