Okay, so I want to create a constructor function in javascript which will count the total number of instances which are created using this constructor.
var Component = function(name) {
this.name = name;
this.add = function(){this.prototype.countInstances++;};
this.add();
};
and
Component.prototype.countInstances=0;
As I understand it correctly, the countInstances variable is added to the prototype and will act like a static copy for all the instances and will act as my counter.
The problem with this code is that since I'm declaring the countInstances after the constructor, I'm getting an error in the constructor code itself. How to correct this??
No, it will be, in effect, a default value for instances, not a "static." If you put it on
Component.prototype
, all instances will inherit it via the prototype chain, but changing it via an instance will give that instance its own copy of it. Example:No, the problem is that your instances have no
this.prototype
object. Theprototype
property on the function is not copied as aprototype
property on instances; it's assigned to them as their prototype, which (somewhat confusingly) isn't calledprototype
. For a long time it didn't have a name outside the spec at all. You can access it viaObject.getPrototypeOf(this)
or (this will be standard for browser-based JavaScript as of the next spec) the__proto__
property.But putting it on the prototype probably doesn't make sense. I'd just use a property on the function itself:
But you said you wanted to count the number of objects created by the constructor; the above counts the number of times the
add
method is called. To count the number of instances created by the constructor, increment it in the constructor: