There are certain mistakes in your code and you need to fix them first to achieve what you want. First you have a mistake in defining your function, there is an extra =
sign there, these are all the possible ways to define your function:
function ObjectName (prop1,prop2){
this.prob1=prob1
this.prob2=prob2
}
var ObjectName = function (prop1,prop2){
this.prob1=prob1
this.prob2=prob2
};
var ObjectName = function ObjectName (prop1,prop2){
this.prob1=prob1
this.prob2=prob2
};
The other point is related to this
keyword. Whenever you use this
keyword in your function you are able to use your functions in couple of certain ways:
1- Using new
keyword: It seems based on what you mean by instances, your code is missing a new
keyword:
function ObjectName(prop1,prop2){
this.prob1=prob1
this.prob2=prob2
}
var object1=new ObjectName(
"11",
"12");
var object2=new ObjectName(
"21",
"22");
2- Using call
or apply
:
var object1 = {}
ObjectName.call(object1,
"11",
"12");
or:
var object2 = {}
ObjectName.apply(object2,[
"21",
"22"
]);
Or if you don't want to use new
keyword, to have a safe object creation process you better use Object.create(prototypeObject)
like:
var object1 = Object.create(ObjectName.prototype);
ObjectName.call(object1,
"11",
"12");
This would allow you to define your other methods and variables in ObjectName.prototype
like:
ObjectName.prototype.myVar = "Anything";
At the end To loop over all the instance you should first store them somewhere. You could do it like:
function ObjectName(prop1,prop2){
ObjectName.instances.push(this);
this.prob1=prob1
this.prob2=prob2
}
ObjectName.instances = [];
Then you can loop over ObjectName.instances
which is an array consisting all of your instances.
var instance,
i = 0, l = ObjectName.instances.length;
for ( ; i < l ; i++ ){
instance = ObjectName.instances[i];
//document.write(objectname.key.prob1)}
console.log(instance.prob1);
}
NEVER use document.write
for your outputs, it has different effects in different situation on your page, depending on when you call it. Create you DOM objects like div
elements and put your data inside them.
The other point that is worth nothing is the way I have defined your function in camel-case, with a upper first letter. This is kind of convention for creating JavaScript functions that are going to be used as a constructor.