[英]Create instance of ES6 class from JSON result
從 JSON 對象創建 ES6 類實例的最簡單方法是什么? 例如,給出如下內容:
class Foo
constructor(bar) {
this.bar = bar
}
frob() {
console.log(`frobbed ${this.bar}`)
}
}
和一個 API 調用返回:
{ "bar": "baz" }
我怎樣才能得到這樣的東西?
let foo = new Foo("baz")
即,類似於:
async function frobResult() {
let result = await fetch('/foo') // returns { "bar": "baz" }
// ...magic happens here?
result.frob() // logs "frobbed baz" to console
}
顯然,我可以讓構造函數取出 JSON 對象並從中拉出bar
,或者編寫一個執行類似操作的工廠函數,但我寧願不必按名稱調用每個屬性,理想情況下我寧願不要必須循環getOwnPropertyNames()
或類似的。 例如,有什么方法可以讓我對 JSON 對象進行猴子補丁來擴展Foo
嗎?
ETA:在答案中, Rahul Kumar 的Object.setPrototypeOf()
正是我所要求的猴子補丁解決方案,但是當您不僅有一個類,而且有一個復雜的對象時, CertainPerformance 的Object.assign()
特別有用不想丟失的狀態,例如 Vue 組件。
使用Object.create
創建一個對象,其內部原型為Foo.prototype
,其自身的屬性是 API 對象的:
class Foo { constructor(bar) { this.bar = bar } frob() { console.log(`frobbed ${this.bar}`) } } const apiObj = { "bar": "baz" }; const instance = Object.assign(Object.create(Foo.prototype), apiObj); console.log(instance); instance.frob();
使用Object.setPrototypeOf()
方法將result
對象的原型設置為Foo
的原型。
class Foo { constructor(bar) { this.bar = bar } frob() { console.log(`frobbed ${this.bar}`); } } function frobResult() { let result = { bar: "baz" }; // Mock fetch api result Object.setPrototypeOf(result, Foo.prototype); console.log(result); result.frob(); } frobResult();
您可以將對象或其屬性傳遞給構造函數。
async function frobResult() {
const result = await fetch('/foo') // returns { "bar": "baz" }
// ...magic happens here?
const foo = new Foo(result.bar);
foo.frob() // logs "frobbed baz" to console
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.