Home >Web Front-end >JS Tutorial >How to Cast Plain JavaScript Objects into Instances of Classes?
Creating real instances from plain objects in JavaScript is possible but comes with certain challenges. Let's explore a practical scenario and its solution.
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().
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.
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 ...; };
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.
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]); } }
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!