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

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

DDD
DDD原創
2024-10-18 12:05:28896瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn