2017-07-21 31 views
0

我將Foo實例寫入JSON並恢復回來。然後,我嘗試使用實例的方法,但我得到的錯誤:如何正確地將_foo投射到`Foo`類型?

class Foo{ 
 
\t constructor(name,surname){ 
 
\t \t this.name=name; 
 
    this.surname=surname; 
 
    }; 
 
    fullName(){ 
 
    \t 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類型?

回答

0

// JS6 
 
class Foo{ 
 
\t constructor(name,surname){ 
 
\t \t this.name=name; 
 
\t \t this.surname=surname; 
 
\t }; 
 
    fullName(){ 
 
    \t 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());

0

你可以使用一個Object.assign(...)

function foo() { } 

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