Raymond Raymond - 6 months ago 9
Javascript Question

In Javascript, is there a way to count how many created objects I've made?

For instance, let's say I'm really hungry so I just keep making pancakes!

var Buttermilk = new Pancake("Buttermilk", "Delicious");
var ChocolateChip = new Pancake("Chocolate Chip", "Amazing");
var BlueBerry = new Pancake("Blue Berry", "The Best");
var SnozBerry = new Pancake("Snoz Berry", "What's a Snoz Berry?");


How would I count how many pancakes I just made without manually doing it? Is there a code that says "There are this many variables that are of the Pancake variety"?

Answer

You can have static properties in javascript classes. You can either hide them in closures that way:

var Pancake = (function() {
    var instances = 0;
    return function(a, b) {
       this.a = a;
       this.b = b;
       instances++;

       Pancake.prototype.instances = function() { // equivalent of a static method
           return instances;
       }
    };
}());

or put them in the object prototype:

var pancake = function(a, b) {
    this.a = a;
    this.b = b;
    pancake.prototype.count = pancake.prototype.count ? pancake.prototype.count + 1 : 1; // equivalent of a static property
}

You can also "override" the constructor, by implementing some kind of "inheritance", such as in this fiddle:

var Pancake = function(a, b) {
	this.a = a;
  this.b = b;
};

var before = Pancake.prototype;
var Pancake = function() {
	console.log("overriden");
	Pancake.prototype.instances = Pancake.prototype.instances ? Pancake.prototype.instances + 1 : 1; // here you should restore the whole prototype
  return before.constructor.apply(this, arguments);
};


var a = new Pancake("a", "b");
document.write(Pancake.prototype.instances + "<br />");
var b = new Pancake("c", "d");
document.write(Pancake.prototype.instances + "<br />");

document.write(JSON.stringify(a) + "<br />");
document.write(JSON.stringify(b) + "<br />");