Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the instances of an object?

Tags:

javascript

If i have a Javascript object defined as:

function MyObj(){};

MyObj.prototype.showAlert = function(){
   alert("This is an alert");
   return;
};

Now a user can call it as:

var a = new MyObj();
a.showAlert();

So far so good, and one can also in the same code run another instance of this:

var b = new MyObj();
b.showAlert();

Now I want to know, how can I hold the number of instances MyObj? is there some built-in function?

One way i have in my mind is to increment a global variable when MyObj is initialized and that will be the only way to keep track of this counter, but is there anything better than this idea?

EDIT:

Have a look at this as suggestion here:

enter image description here

I mean how can I make it get back to 2 instead of 3

like image 830
Johnydep Avatar asked Sep 11 '12 22:09

Johnydep


People also ask

How do you count the number of instances or objects created for a class?

In order to count the number of objects, we need to add a count variable in the constructor and increments its value by 1 for each invocation. Remember that the variable count must a class-level variable.

How do you count the number of instances in Python?

The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.


2 Answers

Using ES6 Classes MDN syntax - we can define a static method:

The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.

class Item {

  static currentId = 0;    
  _id = ++Item.currentId;  // Set Instance's this._id to incremented class's ID
                           // PS: The above line is same as:
                           // constructor () { this._id = ++Item.currentId; }
  get id() {               
    return this._id;       // Getter for the instance's this._id
  }
}

const A = new Item(); // Create instance (Item.currentId is now 1)
const B = new Item(); // Create instance (Item.currentId is now 2)
const C = new Item(); // Create instance (Item.currentId is now 3)

console.log(A.id, B.id, C.id);                     // 1 2 3
console.log(`Currently at: ${ Item.currentId }`);  // Currently at: 3

PS: if you don't want to log-expose the internal currentId property, make it private:

static #currentId = 0; 
_id = ++Item.#currentId;

Here's an example with constructor and without the getter:

class Item {

  static id = 0;
  
  constructor () {
    this.id = ++Item.id;
  }

  getID() {               
    console.log(this.id);
  }
}

const A = new Item(); // Create instance (Item.id is now 1)
const B = new Item(); // Create instance (Item.id is now 2)
const C = new Item(); // Create instance (Item.id is now 3)

A.getID();   B.getID();   C.getID();       // 1; 2; 3
console.log(`Currently at: ${ Item.id }`); // Currently at: 3
like image 66
Roko C. Buljan Avatar answered Sep 25 '22 17:09

Roko C. Buljan


There is nothing built-in; however, you could have your constructor function keep a count of how many times it has been called. Unfortunately, the JavaScript language provides no way to tell when an object has gone out of scope or has been garbage collected, so your counter will only go up, never down.

For example:

function MyObj() {
  MyObj.numInstances = (MyObj.numInstances || 0) + 1;
}
new MyObj();
new MyObj();
MyObj.numInstances; // => 2

Of course, if you want to prevent tampering of the count then you should hide the counter via a closure and provide an accessor function to read it.

[Edit]

Per your updated question - there is no way to keep track of when instances are no longer used or "deleted" (for example by assigning null to a variable) because JavaScript provides no finalizer methods for objects.

The best you could do is create a "dispose" method which objects will call when they are no longer active (e.g. by a reference counting scheme) but this requires cooperation of the programmer - the language provides no assistance:

function MyObj() {
  MyObj.numInstances = (MyObj.numInstances || 0) + 1;
}
MyObj.prototype.dispose = function() {
  return MyObj.numInstances -= 1;
};
MyObj.numInstances; // => 0
var a = new MyObj();
MyObj.numInstances; // => 1
var b = new MyObj();
MyObj.numInstances; // => 2
a.dispose(); // 1 OK: lower the count.
a = null;
MyObj.numInstances; // => 1
b = null; // ERR: didn't call "dispose"!
MyObj.numInstances; // => 1
like image 35
maerics Avatar answered Sep 23 '22 17:09

maerics