2

can i count an objects? like:

 var student1 = new Student();
student1.name("ziv");
student1.age();
student1.where("a");


 var student2 = new Student();
student2.name("dani");
student2.age();
student2.where("b");

 var student3 = new Student();
student3.name("bari");
student3.age();
student3.where("c");

some function that will count them and return 3 .

thanks :)

zipo_soft
  • 31
  • 1
  • 5

4 Answers4

2

I suppose you mean counting instances. You'll have to track the instances, e.g. using an array

var students = [];
var student1 = new Student()
   ,student2 = new Student();
students.push(students1,students2);
/* later ... */
var nOfStudents = students.length; //=> 2

Another idea would be to add a counter to the Student prototype:

Student.prototype.instanceCnt = 0;

And increment it in the Student constructor for every instance

   //in the Student constructor function
   function Student(){
     this.instanceCnt += 1;
     /* ... */
   }
   // usage example
   var student1 = new Student()
      ,student2 = new Student()
      ,students = student1.instanceCnt; //=> 2
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

No, you would manually need to add a counter in the Student constructor or append each instance to an array and get the length of that array.

F.ex:

var counter;
function Student() {
    counter++; // this will increase every time Student is initialized
    // continue the constructor...
}

Or:

var students = [];
function Student() {
    students.push(this); // this will hold the instance in an array
    // continue the constructor...
}
console.log(students.length);
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • I think the first method is better, because the second one will hold a reference to every Student object ever created and so does not allow the Garbage Collector to free Student objects not used anymore by the actual code. Also, a minor drawback of both methods is that they use a global variable. – Ridcully Dec 25 '12 at 09:21
  • @Ridcully One probably should not worry about the garbage collector in Javascript, and the global variable issue can be removed by using a closure. – Waleed Khan Dec 25 '12 at 09:23
  • @WaleedKhan Why not worry about the garbage collector? You can run out of memory in javascript as easy as in any other language can't you? – Ridcully Dec 25 '12 at 09:31
  • @Ridcully Maybe, but Javascript doesn't have accessible facilities for memory management. – Waleed Khan Dec 25 '12 at 09:34
  • @Ridcully "The main purpose of garbage collection is to allow the programmer *not* to worry about memory management of the objects they create and use" — http://stackoverflow.com/a/864544/344643 – Waleed Khan Dec 25 '12 at 09:35
  • @WaleedKhan That's true, still you should not knowingly create memory leaks, even in Javascript - http://stackoverflow.com/questions/864516/what-is-javascript-garbage-collection/864544#864549 And that's the last I'll say to this topic. – Ridcully Dec 25 '12 at 20:35
1

there is no concept of statics in Javascript, but you can use closures to emulate that functionality.

(function(){

  var numberOfInstances = 0;

  var Student = function(studentName){
    var name = '';

    var _init(){
      name = studentName ? studentName : 'No Name Provided';
      numberOfInstances++;    
    }();

    this.getName = function(){
       return name;
    }; 

    this.getNumberOfInstances = function(){
      return numberOfInstances;
    };

    return this;
  };
})(); 

var student1 = new Student("steve");
var student2 = new Student("sally");
console.log("my name is " + student1.getName());
console.log("my name is " + student2.getName());
console.log("number of students => " + student1.getNumberOfInstances());  
console.log("number of students => " + student2.getNumberOfInstances());  
thescientist
  • 2,906
  • 1
  • 20
  • 15
0

You could write a simple generic Instantiation/Inheritance helper which keeps track of its instances in an Array

Something like this might do it

var base = (function baseConstructor() {

  var obj = {
    create:function instantiation() {
        if(this != base) {
        var instance = Object.create(this.pub);
         this.init.apply(instance,arguments);
         this.instances.push(instance);
        return instance;
        } else {
          throw new Error("You can't create instances of base");
        }
    },
    inherit:function inheritation() {
      var sub = Object.create(this);
      sub.pub = Object.create(this.pub);
      sub.sup = this;
      return sub;
    },
    initclosure:function initiation() {},
    instances: [],
    pub: {}

  };



  Object.defineProperty(obj,"init",{
   set:function (fn) {
     if (typeof fn != "function")
       throw new Error("init has to be a function");
     if (!this.hasOwnProperty("initclosure"))      
       this.initclosure = fn;
    },
    get:function () {
        var that = this;
        //console.log(that)
            return function() {
              if(that.pub.isPrototypeOf(this)) //!(obj.isPrototypeOf(this) || that == this))
                that.initclosure.apply(this,arguments);
              else
                throw new Error("init can't be called directly"); 
             };
    }    

  });


  Object.defineProperty(obj,"create",{configurable:false,writable:false});
    Object.defineProperty(obj,"inherit",{configurable:false,writable:false});
  return obj;
})();

var Student = base.inherit()
    Student.init = function (age) {
    this.age = age;    
    }

var student1 = Student.create(21)
var student2 = Student.create(19)
var student3 = Student.create(24)

    console.log(Student.instances.length) // 3

Heres an example on JSBin

Moritz Roessler
  • 8,542
  • 26
  • 51