Static and Instance Methods in JavaScript



 I thought I quite ‘understood’ inheritance in JavaScript until I got flummoxed while trying to test my understanding. The JS prototypical inheritance model is hugely different from the classical approaches of the languages I started out with; the only way to fix this that I know of is by writing code and after spending hours screaming at my console I finally saw the light Alhamdulilah.

JS is a weakly-typed prototypical language and thus classes aren’t really ‘classes’; instead they are functions which are in turn objects. New objects are created from constructor functions by using the new keyword and this allows you to kind of ‘simulate’ OOP. But mind you; its inheritance model is still different.

 Some sample code that shows this difference between static and instance properties. All object properties are public although can easily make them private by declaring them with var (I added an example); for these private properties you’ll have to add accessors and setters; read this for an explanation of closures and this pattern.


var Person = function (name, age){
//private properties
var priv = {};
//Public properties = name;
this.age = age;
//Public methods
this.sayHi = function(){
// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
alert("I am a Person object ;)");
// An instance method;
// All Person objects will have this method
Person.prototype.setName = function(nameIn) { = nameIn;
// Tests
var per = new Person('John Doe', 22);
//Shows alert
//TypeError: Object [object Object] has no method 'sayName'
//Show alert
//John Doe;
per.setName('Jane Doe');
//Jane Doe;
view rawgistfile1.js hosted with ? by GitHub


It’s interesting to see that static fields cannot be accessed from child context in JavaScript (which makes sense); Java, however, allows static fields to be accessed from object context; this is kinda weird as the objects don’t really ‘have’ that variable.

Here’s a quote from the Java Tutorials website:

Note: You can also refer to static fields with an object reference like


but this is discouraged because it does not make it clear that they are class variables.

One tip: don’t just read code and assume you understand it. Sure, you can always convince yourself that you ‘know’ it. However, if you really want to KNOW it then read it, write it and then try extend it (if you have the time and enthusiasm).

So, what other differences do you know between classical and prototypical inheritance?