Utility functions in JavaScript

We often have JavaScript functions which are used in several pages of our project. Best approach is to store all these functions in a shared JavaScript file, included when necessary.

The usual approach I adopt (and suggest) is to create an utility class like the following one:

function Util () {}

Util.read = function (sel) {
    return jQuery(sel).val();

Util.write = function (sel, val) {

We start to define an empty Class (named Util) by a constructor and then we add to it our functions.
These are “static” like functions which are always available, without the need to create an instance of the class Util (with the new operator).

I save the above code in a util.js file (file name = class name).

How to use the utility functions ?

    // read the value of the element with id myinput
    var val = Util.read('#myinput');

JSLint users: don’t forget to add Util in the globals list ( /*globals Util */ )

Final comment: these approach should be used only for utility methods which do not save internal state
or use global variables. The constructor function should be empty; the functions defined as above (and not via class prototype) cannot access to any
class field.

3 thoughts on “Utility functions in JavaScript

  1. thats a great tip. How can i use JSDoc on this functions so intellisense shows info about them?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s