Javascript array of objects, objects sharing same member array? -


i have array of objects (this object contains array of it's own) i'm not sure why, when push values onto member array of 1 instance of object in array of objects seems push onto other member arrays on other array of objects. have provided code below:

var imagegroup = {   groupname:"",   haz:[] };  var imagehandler = { imagegroupsarray:[],   image_process: function() { //calling function here...  //pushing objects this.imagegroupsarray.push(object.create(imagegroup)); this.imagegroupsarray.push(object.create(imagegroup));  //assigning values this.imagegroupsarray[0].haz.push("dog"); this.imagegroupsarray[1].haz.push("cat");  //should output array 'dog' in console.log(this.imagegroupsarray[0].haz);  //should output array 'cat' in console.log(this.imagegroupsarray[1].haz);  //instead, both of these output ["dog","cat"] //this.imagegroupsarray[1].haz , this.imagegroupsarray[0].haz point same 'haz' array?? } } 

this doesn't happen when try set groupname same way. doing wrong? in advance!

this code:

var imagegroup = {   groupname:"",   haz:[] }; 

creates single object in memory. code:

this.imagegroupsarray.push(object.create(imagegroup)); this.imagegroupsarray.push(object.create(imagegroup)); 

creates 2 new objects (pushing each onto imagegroupsarray). both of these objects have same imagegroup object prototype. knowing how prototypes work lot on one. basically, code:

this.imagegroupsarray[0].haz.push("dog"); this.imagegroupsarray[1].haz.push("cat"); 

looks haz property on each of object.create()ed objects. when can't find it, looks prototype chain , finds on parent object (which same object in both cases). modifications made 1 object will, of course, show in places object referenced (so in both objects pushed imagegroupsarray).

the correct approach declare imagegroup function defines properties:

var imagegroup = function() {     this.groupname = '';     this.haz = []; } 

then use new keyword, instead of object.create():

this.imagegroupsarray.push(new imagegroup()); this.imagegroupsarray.push(new imagegroup()); 

cheeers.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -