Home  >  Article  >  Web Front-end  >  How to Cast Plain JavaScript Objects into Instances of Classes?

How to Cast Plain JavaScript Objects into Instances of Classes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 13:02:02972browse

How to Cast Plain JavaScript Objects into Instances of Classes?

Casting Plain Objects to Class Instances in JavaScript

Creating real instances from plain objects in JavaScript is possible but comes with certain challenges. Let's explore a practical scenario and its solution.

Problem

Consider two classes, Person and Animal. The server returns an array of generic Person objects:

[
  { personName: "John", animals: [{ animalName: "cheetah" }, { animalName: "giraffe" }] },
  { personName: "Smith", animals: [{ animalName: "cat" }, { animalName: "dog" }] }
]

The goal is to cast this object array into a typed array of Person instances to enable calls such as persons[0].Animals[2].Run().

Solution

Creating instances from plain objects involves invoking their constructors and assigning properties correctly.

A general approach is to have constructors accept objects that resemble instances and clone them. Internal instance creation logic is handled by the constructors.

Custom Method

Another solution is to create a static method on the Person class that takes objects and generates instances:

Person.fromJSON = function(obj) {
  // Custom code to create instances based on `obj`
  return ...;
};

Simple Approach for Basic Cases

For simple cases like yours, where there are no constructors and only public properties, you can do this:

var personInstance = new Person();
for (var prop in personLiteral)
  personInstance[prop] = personLiteral[prop];

Or, you can use Object.assign:

var personInstance = Object.assign(new Person(), personLiteral);

Follow a similar approach to create Animal instances.

Other Implementation

Since JSON doesn't convey class information, you'll need to know the object structure in advance. In your case, the implementation would look like this:

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]);
  }
}

Additional Notes

Your Animal class likely defines its run method on the prototype, rather than each instance.

The above is the detailed content of How to Cast Plain JavaScript Objects into Instances of Classes?. 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