Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through each new Object from Constructor

Firstly, sorry for my lack of terminology.

If I have a constructor

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

and I make a few objects from it

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

Can I loop through each new Object made from the myObject class, without putting each new Object into an Array?


would it be possible to add an Instantly Invoking Function to the constructor that adds the Object into an array?

e.g.

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

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

that way any new objects created instantly run this function and get added to the array.

Is this possible? ( current syntax does not work, obviously )


EDIT Coming back to this one year later I can tell you that it IS possible. You just call the function inside the constructor like so:

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 on instantiation and then calling each object's .speak() method directly from the array.

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

like image 359
Josh Stevenson Avatar asked Jul 02 '15 09:07

Josh Stevenson


1 Answers

Without using an array, you can't, it is not the way it is meant to be used.

What you can do though, is watch over each instances created in a 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 = [];
like image 170
axelduch Avatar answered Sep 28 '22 20:09

axelduch