El Ronnoco
El Ronnoco

Reputation: 11912

Static/shared property and method in JavaScript

I'm trying to have a 'class' in JS which tracks how many instances of itself have been instantiated. I am attempting to do so like this...

var myNamespace = {};

myNamespace.myClass = function () {
    //fails here as .getNetInstanceNo() not recognised...
    var instanceNumber = myNamespace.myClass.getNextInstanceNo();

    return {
        instanceNo : function() { return instanceNumber; }        
    }        
};

myNamespace.myClass.InstanceNo = 0; //static property?

//should the class itself have this method added to it...
myNamespace.myClass.prototype.getNextInstanceNo = function () { //static method?
  return myNamespace.myClass.InstanceNo++;  
};

var class1 = new myNamespace.myClass();

alert('class 1 has instance of ' + class1.instanceNo() );

However this fails as the getNextInstanceNo function is not recognised. Even though I think I'm adding it through the myClass.prototype.

What am I doing wrong?

Upvotes: 0

Views: 1213

Answers (1)

Kamy .
Kamy .

Reputation: 66

prototype is an object from which other objects inherit properties, as in when you create an instance of an object and that object doesn't have a property/method, when called, the prototype of the class in which the object belongs to is searched for that property/method, here's a simple example:

function Animal(){};
Animal.prototype.Breathe = true;

var kitty= new Animal();
kitty.Breathe; // true (the prototype of kitty breathes)

var deadCat = new Animal();
deadCat.Breathe = false;
deadCat.Breathe; // false (the deadCat itself doesn't breath, even though the prototype does have breath

As you said yourself, you don't need to define getNextInstanceNo on prototype, since that's not how static methods are defined on JavaScript, leave it right right there on the class itself, instead you can define the instanceNo method on prototype, here's how:

var myNamespace = {};

myNamespace.myClass = function () {
    this.instanceNumber = myNamespace.myClass.getNextInstanceNo();
};

myNamespace.myClass.prototype.instanceNo = function () {
    return this.instanceNumber;
};

myNamespace.myClass.InstanceNo = 0; 

myNamespace.myClass.getNextInstanceNo = function () { 
    return myNamespace.myClass.InstanceNo++;
};

var class1 = new myNamespace.myClass();

alert('class 1 has instance of ' + class1.instanceNo());

Upvotes: 4

Related Questions