Javascript 如何正确地将_foo转换为'foo'类型?

Javascript 如何正确地将_foo转换为'foo'类型?,javascript,Javascript,我将Foo实例写入JSON并恢复。然后,我尝试使用instance的方法,但出现错误: class-Foo{ 建造师(姓名){ this.name=name; 这个。姓=姓; }; 全名(){ 返回this.name+“”+this.姓氏; }; }; 设foo=newfoo('John','Smith'); log(foo.fullName()); 让json=json.stringify(foo); 让foo=JSON.parse(JSON); Object.setPrototypeOf(

我将
Foo
实例写入JSON并恢复。然后,我尝试使用instance的方法,但出现错误:

class-Foo{
建造师(姓名){
this.name=name;
这个。姓=姓;
};
全名(){
返回this.name+“”+this.姓氏;
};
};
设foo=newfoo('John','Smith');
log(foo.fullName());
让json=json.stringify(foo);
让foo=JSON.parse(JSON);
Object.setPrototypeOf(_-foo,Object.getPrototypeOf(foo));
//未捕获的TypeError:\u foo.fullName不是函数

log(_foo.fullName())您可以使用
对象。分配(…)

//JS6
福班{
建造师(姓名){
this.name=name;
这个。姓=姓;
};
全名(){
返回this.name+“”+this.姓氏;
};
};
设foo=newfoo('John','Smith');
log(foo.fullName());
让json=json.stringify(foo);
让foo=JSON.parse(JSON);
setPrototypeOf(_-foo,foo.prototype);
log(_foo.fullName())
function foo() { }

const parsedFoo = Object.assign(new foo(), JSON.parse(myJson));
// parsedFoo instanceof foo === true