Home > Web Front-end > JS Tutorial > body text

How to Cast Generic Objects to Typed Instances in JavaScript?

DDD
Release: 2024-10-18 12:05:28
Original
896 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!