Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

EDIT:

Thank you for the answers! I was specifically looking for a simple way to quickly count the amount of times I created an object with a small amount of code. And that is what I got, thank you!

like image 481
Raymond Avatar asked Feb 08 '23 01:02

Raymond


1 Answers

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 />");
like image 92
Regis Portalez Avatar answered Feb 11 '23 01:02

Regis Portalez