如何正确地将_foo转换为`Foo`类型?

时间:2017-07-21 11:51:00

标签: javascript

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

class Foo{
	constructor(name,surname){
		this.name=name;
    this.surname=surname;
  };
  fullName(){
  	return this.name + ' ' + this.surname;
  };
};

let foo = new Foo('John', 'Smith');
console.log(foo.fullName());

let json = JSON.stringify(foo);
let _foo = JSON.parse(json);

Object.setPrototypeOf(_foo, Object.getPrototypeOf(Foo));

// Uncaught TypeError: _foo.fullName is not a function
console.log(_foo.fullName());

如何正确地将_foo转换为Foo类型?

2 个答案:

答案 0 :(得分:0)

您可以使用Object.assign(...)

function foo() { }

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

答案 1 :(得分:0)

// JS6
class Foo{
	constructor(name,surname){
		this.name=name;
		this.surname=surname;
	};
  fullName(){
  	return this.name + ' ' + this.surname;
  };
};

let foo = new Foo('John', 'Smith');
console.log(foo.fullName());

let json = JSON.stringify(foo);
let _foo = JSON.parse(json);

Object.setPrototypeOf(_foo, Foo.prototype);

console.log(_foo.fullName());