Casting Objects to Class Instances in JavaScript
Many cases arise when developers encounter the need to cast plain JavaScript objects, typically received from a server response, into specific class instances for further processing. This requirement arises when the objects received from the server lack the necessary methods and properties associated with the class they represent.
Prerequisites
To cast objects into class instances, we must first understand the following:
Solution
A robust solution is to ensure that every constructor can accept objects resembling instances (including actual instances) and clone them appropriately. This ensures that the instance creation logic is correctly handled.
An alternative and more efficient approach is to create a static method within the class to convert objects into instances:
Person.fromJSON = function(obj) { // Custom code for creating instances of Person return …; };
Specific Example
Consider the following simplified example:
function Person() { this.personName = ""; this.animals = []; } function Animal(){ this.animalName = ""; this.run = function(meters){ ..... } }
To convert the JSON response, we can use the following approach:
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]); } }
Note: The provided run method should be added to the Animal.prototype object rather than individual instances.
The above is the detailed content of How to Cast Objects to Class Instances in JavaScript. For more information, please follow other related articles on the PHP Chinese website!