1

I want to keep track of how many objects have been created using my constructor function. Currently I'm getting the number by placing a humanCount variable in the global namespace. But, it doesn't look good to me. My code is:

var humanCount = 0;

function Human(name, age){
    this.name = name;
    this.age = age;
    humanCount++;
};

var john = new Human("JOHN", 35);
console.log(humanCount); // prints 1 

var jane = new Human("JANE", 28);
console.log(humanCount);  // prints 2

Any other way to achieve the functionality?

Sajib Biswas
  • 433
  • 4
  • 13
  • May I ask why you want to know this statistic? – Ben Rondeau Jan 07 '17 at 07:01
  • You don't have to use global scope if you don't want to. You can create as many "intermediate" scopes as you like. You can make that value also a property of `Human`. There are lots of possibilities. – Felix Kling Jan 07 '17 at 07:01
  • Its not about public/private or scoping issue. Its about creating a variable which will keep track of how many instances are being created. @felixKling – Sajib Biswas Jan 07 '17 at 07:08
  • If your question is not about scope or visibility, then what is it about? Can you elaborate on the "it doesn't look good to me" part? What doesn't look and why? – Felix Kling Jan 07 '17 at 07:10
  • I am looking for a solution which gives this functionality by attaching a variable to Object/Prototype etc. ( i want to avoid attaching it to global object) Sir. – Sajib Biswas Jan 07 '17 at 07:15

2 Answers2

2

You could make the counter a property of the "class" (the constructor):

function Human(name, age){
    this.name = name;
    this.age = age;
    Human.count++;
};

Human.count = 0;

Or you could make it a property of the prototype:

function Human(name, age){
    this.name = name;
    this.age = age;
    Human.prototype.count++;
};

Human.prototype.count = 0;
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
trincot
  • 317,000
  • 35
  • 244
  • 286
1

Create humanCount property like:

function Human(name, age){
    this.name = name;
    this.age = age;
    Human.humanCount = (Human.humanCount || 0) + 1;
};
nitishagar
  • 9,038
  • 3
  • 28
  • 40