consider this simple typescript class
class foo {
public Name: string;
constructor(name: string) {
this.Name = name;
}
public bar(): string {
return this.Name;
}
}
var test = new foo("foo");
var deserialized = JSON.parse(JSON.stringify(test));
deserialized.bar();//not defined. expected
behavior is totally expected, but what should I do to get the method back?
I looked around and found two candidates: Object.create
and Object.setPrototypeOf
I can either do
var test1 = Object.setPrototypeOf(deserialized, foo.prototype);
or
var test2 = Object.create(foo.prototype)
test2 = Object.assign(test2, deserialized);
Both of them seem to work. Is it the right way to do this? is there any danger for playing with the prototype like this? or is there a better way to achieve this?