Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  116] [ 1]  / answers: 1 / hits: 25119  / 12 Years ago, sat, august 4, 2012, 12:00:00
function Person() {
var self = this;

self.personName=;
self.animals=[];
}

function Animal(){
var self=this;

self.animalName=;
self.run=function(meters){
.....
}
}


Server response:



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


I'm getting Person array from server. I want to cast generic Person array to typed Person array. So I can use



 persons[0].Animals[2].Run();


I founded Javascript's



 Object.create(Person,person1);


But I want cross-browser version of it with array support



  ObjectArray.create(Person,persons);


or



 Object.create(Person[],persons);

More From » casting

 Answers
17

Creating an object in JavaScript requires the invocation of its constructor. So, at first you will need to find the correct arguments, which may not always be just properties. After that, you can reassign all public properties from the JSON-parsed object to the created instances.



A general solution would be that every constructor accepts any objects that look like instances (including real instances) and clones them. All the internal logic needed to create proper instances will be located in the right place then.



Or even better than overloading the constructor might be to create a static method on your class that takes objects and creates instances from them:



Person.fromJSON = function(obj) {
// custom code, as appropriate for Person instances
// might invoke `new Person`
return …;
};





Your case is very simple, as you don't have any arguments and only public properties. To change {personName:John,animals:[]} to an object instance, use this:



var personLiteral = ... // JSON.parse(...);
var personInstance = new Person();
for (var prop in personLiteral)
personInstance[prop] = personLiteral[prop];


You can also use Object.assign functionality (or e.g. jQuery.extend pre-ES6) for this:



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


The creation of the Animal instances works analogous.



As JSON does not transport any information about the classes, you must know the structure before. In your case it will be:



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


Btw, your run methods seems likely to be added on the Animal.prototype object instead of each instance.


[#83853] Friday, August 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dannyc

Total Points: 517
Total Questions: 106
Total Answers: 116

Location: Netherlands
Member since Mon, Jun 7, 2021
3 Years ago
;