简体   繁体   English

javascript从已解析的对象调用Json Parse

[英]javascript calling Json Parse from the parsed object

I have a Javascript class in ES6, and I want to write a LoadFromJson method. 我在ES6中有一个Javascript类,并且我想编写一个LoadFromJson方法。

the problem is that JSON.parse return an object and I cannot write : 问题是JSON.parse返回一个对象,我不能写:

//MyObject.loadFromJson method
loadFromJson(JsonString)
 {
   this=JSON.parse(jsonString); //INVALID//
 }

How can I achieve this from within my class. 我如何在课堂上实现这一目标。 I know I could write : 我知道我可以写:

myObject = JSON.parse(jsonString);

but that's not what I want, I need : 但这不是我想要的,我需要:

myObject = new MyObjectClass();
myObject.loadFromJson(JsonString);

I want to implement an "undo mechanism" in my object and to be able to save / restore the object. 我想在我的对象中实现“撤消机制”,并能够保存/恢复该对象。

You can't assign to this . 您不能分配到this Here is an example that copies all the attributes from the parsed object. 这是一个从已解析的对象复制所有属性的示例。

class MyObjectClass {
  loadFromJSON(jsonString) {
    const parsed = JSON.parse(jsonString);
    for (const key in parsed) this[key] = parsed[key];
  }
}

const myObject = new MyObjectClass();
myObject.loadFromJSON('{"a":2,"b":null,"c":"abc"}');
console.log(myObject);

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

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