javascript - Loop through each new Object from Constructor -


firstly, sorry lack of terminology.

if have constructor

function myobject(name, value){     this.name = name;     this.value = value; } 

and make few objects it

var 1 = new myobject("one", 1); var 2 = new myobject("two", 2); 

can loop through each new object made myobject class, without putting each new object array?


would possible add instantly invoking function constructor adds object array?

e.g.

function myobject(name, value){     this.name = name;     this.value = value;      this.addtoarray = function(){         thearray.push(this);        // iife     }();  } 

that way new objects created instantly run function , added array.

is possible? ( current syntax not work, )


edit coming 1 year later can tell possible. call function inside constructor so:

function myobject(name, value){     this.name = name;     this.value = value;      this.addtoarray = function(){         thearray.push(this);     };      this.addtoarray();  } 

here example of in jsfiddle, pushing each object array on instantiation , calling each object's .speak() method directly array.

https://jsfiddle.net/panomosh/8bpmrso1/

without using array, can't, not way meant used.

what can though, watch on each instances created in static member of myobject class

function myobject(name, value){     this.name = name;     this.value = value;      this.watch(); }  myobject.prototype.watch = function () {     if (myobject.instances.indexof(this) === -1) {         myobject.instances.push(this);     } };  myobject.prototype.unwatch = function () {     myobject.instances.splice(myobject.instances.indexof(this), 1); };  myobject.instances = []; 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - How to Hide Date Menu from Datepicker in yii2 -