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 CalendarreadableTime(beginDate, endDate) function. Great! But what if the object name Calendar changes for BestCalendar? The CalendarreadableTime 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.

comments powered by Disqus