Static properties and methods are those that don't change from one instance to another, which can be used without having to create an instance of the class. Let's take a look at an example in Java:
public class Car { public static String make = "Honda"; public void run() { ... } } Car.make; // a static method Car car = new Car(); car.run(); // a normal method
In JavaScript there is no special syntax to denote static members. But we can still have the same syntax as in a "classy" language by using a constructor function and adding properties to it to simulate the syntax as in a "classy" language.
// constructor var Car = function() {}; // a static method Car.getMake = function() { return "Honda"; } //a normal method added to the prototype Car.prototype.getModel = function() { return "Civic"; }
Now let's call these methods. The static getMake() is invoked directly on the constructor, whereas the regular method needs an instance.
// calling a static method Car.getMake(); // "Honda" //creating an instance and calling a method var car = new Car(); car.getModel(); // "Civic"
Attempting to call an instance method statically won't work; same for calling a static method using the instance car object:
typeof Car.getModel; // "undefined" Car.getModel(); // TypeError: Object function () {} has no method 'getModel' typeof car.getMake; // "undefined" car.getMake(); // TypeError: Object [object Object] has no method 'getMake'
Code below shows how you can have the same method being called statically and non-statically and behave slightly different, depending on the invocation pattern.
var Car = function(model) { this.model = model; }; Car.getProperty = function() { var msg = "Honda"; if(this instanceof Car) { msg += " " + this.model; } return msg; } Car.prototype.getProperty = function() { return Car.getProperty.call(this); }
Test a static method call and an instance, non-static call.
Car.getProperty(); // "Honda" var car = new Car("Civic"); car.getProperty(); // "Honda Civic"