Home >Web Front-end >JS Tutorial >How to Cast Generic Objects to Typed Instances in JavaScript?

How to Cast Generic Objects to Typed Instances in JavaScript?

DDD
DDDOriginal
2024-10-18 12:05:281011browse

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.

The above is the detailed content of How to Cast Generic Objects to Typed Instances in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn