Object-Oriented JavaScript Tip: Creating static methods, instance methods
Custom JavaScript objects can have instance methods (function that are associated with a particular JavaScript object), but like other Object-Oriented languages, they can also have static methods, that is functions that are associated with the JavaScript class that created an object, as opposed to the object itself. This is useful in cases where a function (a.k.a. a method) will not be different in different object instances. Let’s look at an example…
Suppose you created a class to handle simple arithmetic calculations:
function Calculator() { }
To begin with, an instance method could be added to this class in one of two ways, either inside the constructor or through the class prototype. In this example, one method called multiply will be created, which returns the product of two values multiplied together. First, implemented in the constructor it looks like:
function Calculator() { this.multiply = function(val1 , val2) { return (val1*val2); } }
Via the class prototype, which is a more readable solution in my opinion, it would look like:
function Calculator() { } Calculator.prototype.multiply = function(val1 , val2) { return (val1*val2); }
Use of this method would then occur through instances of the Calculator class, like so:
var calc = new Calculator(); alert( calc.multiply(4,3) ); //pop-up alert with product of 4 times 3
However, it shouldn’t really be necessary to create an object to use the multiply method, since the method isn’t dependent on the state of the object for its execution. The method can be moved to the class to clean up this code a bit. First the class definition is created, which looks almost identical to the instance method declaration above, with the exception of the prototype keyword being removed:
function Calculator() { } Calculator.multiply = function(val1 , val2) { return (val1*val2); }
Now the multiply method can be called through the class itself, instead of an instance of the class, like so:
alert( Calculator.multiply(4,3) ); //pop-up alert with product of 4 times 3

August 7th, 2009 at 1:51 pm
Thanks for the clear and concise article!
October 5th, 2009 at 9:29 pm
I was looking for a way to create static methods with Dojo and came across this post. Great explanation!
October 20th, 2009 at 10:25 pm
I’m newbie on JavaScript and there’s something that’s not clear to me. It’s about prototyping.
I’m reading “JavaScript, The Definitive Guide” and what I undestand is that methods/properties created using prototype apear has they were part of the instance but they really aren’t. They’re common to all instances from the particular object.
So my question is if they’re considered instance or static.
Thanks,
October 20th, 2009 at 10:44 pm
Hi Victor,
Hmm… I would consider them instance methods, since they are accessible through instances of a class (albeit all instances), whereas a static method is accessible in the class itself.