To address your comment on calling addFunc on all instances in one statement:
To call a certain function on all instances you have to keep track of all the instances. This can be done in the Object definition (Foo constructor).
To have an Object definition (constructor function) keep track of all it's instances is a bit complicated.
If in a function I create 100 Foo instances and the function exits then these instances would go out of scope. But because Foo would keep track of it's instances it has a reference to these instances and therefor even after the function exits these instances will not be garbage collected (go out of scope).
To indicate to Foo that these instances are no longer needed you have to explicitly call destroy on the instances so a reference to that instance is no longer kept in Foo._instances.
Here is some code to demonstrate:
//Object definition of Foo (constructor function)
var Foo=function(e,d) {
this.b=e;
this.c=d;
//saving this instance in Foo._instances
this._instanceId=Foo._instanceCount;
Foo._instances[this._instanceId]=this;
Foo._instanceCount++;
}
//properties of the Object definition
Foo.allAddFunc=function(){
var thing;
for(thing in Foo._instances){
if(Foo._instances.hasOwnProperty(thing)){
Foo._instances[thing].addFunc();
}
}
};
//container for all instances of Foo
Foo._instances={};
//does not refllect the actual count
// used to create _instanceId
Foo._instanceCount=0;
//prototype of Foo (used for foo instances)
Foo.prototype.addFunc=function() {
this.d=this.b+this.c;
};
//when a Foo instance is no longer needed
// you should call destroy on it
Foo.prototype.destroy=function(){
delete Foo._instances[this._instanceId];
};
(function() {
var bas=new Array(10),i=0,len=bas.length;
//create instances
for(;i<len;i++){
bas[i]=new Foo(i,i*2);
};
//do something with all instances
Foo.allAddFunc();
//bas[] will go out of scope but all instances of
// Foo will stay in Foo_instances, have to explicitely
// destroy these instances
for(i=0,len=bas.length;i<len;i++){
console.log("bas.d at "+i+":",bas[i].d);
//Foo instance at bas[i] no longer needed
// destroy it
bas[i].destroy();
};
}());
About prototype: https://stackoverflow.com/a/16063711/1641941