0

I have a Javascript class in ES6, and I want to write a LoadFromJson method.

the problem is that JSON.parse return an object and I cannot write :

//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.

1
  • Just curious, why can't you do myObject=JSON.parse(jsonString) and need a separate loadFromJson method? Commented Aug 17, 2016 at 0:06

1 Answer 1

2

You can't assign to 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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.