首頁 > web前端 > js教程 > 如何在 JavaScript 中將通用物件轉換為類型化實例?

如何在 JavaScript 中將通用物件轉換為類型化實例?

DDD
發布: 2024-10-18 12:05:28
原創
983 人瀏覽過

How to Cast Generic Objects to Typed Instances in JavaScript?

Casting Generic Objects to Typed Instances in JavaScript

Problem Statement:

JSON responses from servers often contain plain objects that represent class instances. Casting these generic objects to typed instances allows for utilizing their class methods and accessing typed data.

Solution:

Creating object instances requires invoking their constructors. However, JSON data lacks constructor information, so a different approach is necessary.

1. Iterative Cloning:

This approach involves cloning the properties of the plain objects to newly created instances:

<code class="javascript">var personLiteral = ...; // JSON.parse("...");
var personInstance = new Person();
for (var prop in personLiteral)
    personInstance[prop] = personLiteral[prop];</code>
登入後複製

2. Using Object.assign:

Object.assign can be used to accomplish the same task more concisely:

<code class="javascript">var personInstance = Object.assign(new Person(), personLiteral);</code>
登入後複製

For more complex objects with nested structures, iterate through the properties and apply the same cloning process recursively.

3. Custom Constructor Cloning:

Every constructor can be extended to accept plain objects and clone them, handling any necessary logic:

<code class="javascript">Person.fromJSON = function(obj) {
    // custom code, as appropriate for Person instances
    // might invoke `new Person`
    return …;
};</code>
登入後複製

Example:

In your specific scenario, apply the cloning process to both the Person and Animal objects:

<code class="javascript">var persons = JSON.parse(serverResponse);
for (var i=0; i<persons.length; i++) {
    persons[i] = $.extend(new Person, persons[i]);
    for (var j=0; j<persons[i].animals; j++) {
        persons[i].animals[j] = $.extend(new Animal, persons[i].animals[j]);
    }
}</code>
登入後複製

Remember that run methods should be added to the Animal prototype rather than individual instances.

以上是如何在 JavaScript 中將通用物件轉換為類型化實例?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板