0

My confusion stems from the last line of this code snippet:

function Animal(name) {
    Animal.count = Animal.count+1||1;// static variables, use function name "Animal"
    this.name = name; //instance variable, using "this"
}

Animal.showCount = function () {//static method
    alert(Animal.count)
}

Animal.prototype.showName=function(){//instance method
    alert(this.name);
}

var mouse = new Animal("Mickey");
var elephant = new Animal("Haddoop");

Animal.showCount();  // static method, count=2
mouse.showName();//instance method, alert "Mickey"
mouse.showCount();//Error!! mouse.showCount is not a function, which is different from  Java

Question: Why isn't mouse.showCount() a function?

1
  • 2
    Because you're putting it on the Animal object, not all Animal objects. Commented Apr 4, 2015 at 14:35

1 Answer 1

3

JavaScript doesn't have static methods in a traditional sense. All you're doing is assigning a function as a property of another function (the constructor). Remember, functions are objects in JS.

So there's no direct relationship between the object instances created from a constructor and the constructor itself. The only* relationship is between the instance and the constructor function's .prototype object.

If you were to overwrite the .prototype of the constructor, then there wouldn't even be that indirect relationship. So basically the constructor just acted as a temporary "match maker" between its .prototype and the new object instance being created. After that, the constructor plays no role.


* The instanceof operator makes it seem as though there's a connection, but it's really just comparing the objects in the instance's prototype chain to the .prototype object of the constructor, so it's still an indirect relationship and one that can be broken.

Sign up to request clarification or add additional context in comments.

4 Comments

I wonder what the "traditional sense" of a static method is… it never made sense to me that one could access class methods on instances.
@Bergi: Yeah I'm not much of a classical object oriented programmer but I don't think that in those environments a static method is anything like assigning a function to a property of another function. That's mostly what I was getting at. :-)
@Bergi Agreed. In Java I would argue that a reason could be that it's the "only" way to allow an instance method to access a static method of the same class without specifying the class name (since doFoo() is equivalent to this.doFoo() which is instance access). Not that it couldn't be solved differently, but it's about the best argument I could come up with…
@Lye Fish: Very helpful response. Cleared up some massive JavaScript confusion.

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.