Loop through each new object from the constructor

First, sorry for the lack of terminology.

If I have a constructor

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

and I make several objects out of it

 var One = new myObject("One", 1); var Two = new myObject("Two", 2); 

Is it possible to scroll through each new object from the myObject class without putting each new object into an array?


Is it possible to add an instantly calling function to the constructor that adds an object to an array?

eg.

 function myObject(name, value){ this.name = name; this.value = value; this.addToArray = function(){ theArray.push(this); // this is the IIFE }(); } 

Thus, any newly created objects instantly start this function and are added to the array.

Is it possible? (current syntax doesn't work, obviously)


EDIT Coming back to this in a year, I can tell you that this is possible. You simply call the function inside the constructor as follows:

 function myObject(name, value){ this.name = name; this.value = value; this.addToArray = function(){ theArray.push(this); }; this.addToArray(); } 

Here is an example of this in JSFIDDLE, pushing each object into an array when creating an instance, and then calling each object .speak() method directly from the array.

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

+6
source share
3 answers

You cannot use an array, this does not mean that it is intended to be used.

What you can do is keep track of each instance created in the 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 = []; 
+1
source

No, you can’t. You cannot do this with almost all programming languages.

In the constructor, you can save a link to each object that you created into an array / map so that you can iterate over them at any time. This, however, does not allow all objects of this class to collect garbage, so use it with caution.

WeakMap in JavaScript stores only a weekly link to the keys, but in turn does not allow you to iterate over all keys. So this is also not an option.

+1
source
 var MyClass = (function() { var _instances = []; function MyClass(name, value) { _instances.push(this); this.name = name; this.value = value; } MyClass.each = function(cb) { for (var i in _instances) { if (_instances.hasOwnProperty(i)) { cb(_instances[i]); } } } return MyClass; })(); new MyClass('John', 10); new MyClass('James', 20); MyClass.each(function(item) { console.log(item); }); 
0
source

All Articles