How to do class functions in javascript (aka static or shared functions)

One of the really concept of the object-oriented programming is the class functions but they are also known as static functions (Java, php, C++) or shared functions (.NET).

Why using class method?

Class methods help you keeping your code clean by centralizing your functions. Example, you create a calendar object that formats a string from two dates to have readable time difference (example, input : “2007-08-13″ and “2007-08-16″, output : “begins august 13th 2007 and ends 3 days later”).

Sure you can create a readableTime(beginDate, endDate) function. First problem is that there may be another function with that name. Second problem? If another programmer works on the code that makes a call to readableTime function, how does he knows that it comes from the javascript file containing the Calendar object?

So, you could create a Calendar_readableTime(beginDate, endDate) function. Great! But what if the object name Calendar changes for BestCalendar? The Calendar_readableTime function won’t have the good suffix.

The solution is to use a class function so the call to the readableTime function will look like this : Calendar.readableTime(beginDate, endDate). Nice looking and clean code.

How to create a class function

First, you create a class

[source:javascript]
function Calendar() {
}
[/source]

Second, you add the class function

[source:javascript]
function Calendar() {
}

Calendar.readableTime = function() {
// Code here
}
[/source]

Then, it’s ready to be called in your code

[source:javascript]
var cal = new Calendar();
var beginDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + 3); // Add three days to endDate

var stringTime = Calendar.readableTime(beginDate, endDate);
[/source]

Difference with other languages

In many other languages, your class functions are callable from an instantiated object like this.

[source:javascript]
var cal = new Calendar();
var beginDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + 3); // Add three days to endDate

// I call cal.readableTime and it doesn’t work!
var stringTime = cal.readableTime(beginDate, endDate);
[/source]

In javascript, it doesn’t work because the function readableTime is assigned to the class only and is not referenced in the instances of the class.

To give the access to the readableTime function on the instance of an object is to create the function this way :

[source:javascript]
function Calendar() {
}

Calendar.readableTime = new function() {
// Code here
}

// Here’s the magic
Calendar.prototype.readableTime = Calendar.readableTime;
[/source]

By assigning the function to the prototype, each object of the Calendar type will have the readableTime function.

  • http://octoberdan.com Octoberdan

    [code]
    Calendar.readableTime = new function() {
    // Code here
    }
    [/code]

    Should be

    [code]
    Calendar.readableTime = function() {
    // Code here
    };
    [/code]

  • http://octoberdan.com Octoberdan

    Thank you though for the help. It pointed me in the right direction…

  • http://www.javascriptkata.com/2007/04/04/how-to-make-a-singleton/ How to make a singleton in javascript | Javascript Kata

    [...] Before writing a singleton, you need to know about creating objects and static functions. [...]

  • http://www.surroundsounddj.com toronto wedding dj

    If you define a class method (not an instance method) called init it will be automatically called when the class is created. Constructor functions are never called during the prototyping phase (subclassing).

  • http://rezanachmad.wordpress.com/2011/04/08/kelas-statis-pada-javascript/ Kelas Statis pada Javascript | Welcome to Rezan's Blog
  • http://www.sleevetattoodesigns.net sleeve tattoo designs

    calling LoadControl isn't seen by the compiler as being an explicit instance of the class. What's not explicit about using LoadControl to create a new control from a file. tried creating a new user control and initializing it, then setting it to a different control with LoadControl to no avail.

  • http://www.jmfdisco.co.uk/ Wedding DJ

    I’ll see if I can use it on my [url=http://www.jmfdisco.co.uk]Wedding DJ[/url] website

  • http://twitter.com/joe_bolla Joseph Bolla

    You could Implement Polymorphism like this in JavaScript:

    /** This is our Person class */

            Person = function (id, name, age) {
                this.id = id;
                this.name = name;
                this.age = age;
               // alert(‘A new person has been accepted’);
            }

            /* definition of our Person class */
            Person.prototype = {
                /** wake person up */
                wake_up: function () {
                    alert(‘A person is awake’);
                },

                /** retrieve person’s age */
                get_age: function () {
                    return this.age;
                }
            }

            Inheritance_Manager = {};

            Inheritance_Manager.extend = function (subClass, baseClass) {
                function inheritance() { }
                inheritance.prototype = baseClass.prototype;
                subClass.prototype = new inheritance();
                subClass.prototype.constructor = subClass;
                subClass.baseConstructor = baseClass;
                subClass.superClass = baseClass.prototype;
            }

            Manager = function (id, name, age, salary) {
                Manager.baseConstructor.call(this, id, name, age);
                this.salary = salary;
               // alert(‘A manager has been registered.’);
            }

            Inheritance_Manager.extend(Manager, Person);

            Manager.prototype = {
                wake_up: function () {
                    alert(‘I am in control’);
                }
            }

            var arrPeople = new Array();
            arrPeople[0] = new Person(1, ‘Joe Tester’, 26);
            arrPeople[1] = new Manager(1, ‘Joe Tester’, 26, ’20.000′);

            for (var i in arrPeople) {
                arrPeople[i].wake_up();
                alert(arrPeople[i].get_age());
            }

    View full article with comments: here