0

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?

1
  • In can solve this by simply not adding the method to .prototype - but I thought this was pretty much what prototype was for?! Commented Apr 18, 2012 at 15:05

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

1 Comment

So in my post where I say var instanceNumber = myNamespace.myClass.getNextInstanceNo() - what is it actually trying to do that it fails to do and why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.