Nima Dilmaghani’s Technology Blog

Why object oriented JavaScript is not always a good idea

Posted in cookie, javascript, web development by nimad on September 7, 2007

JavaScript is not inherently an object oriented language. When we build object oriented constructs, we add additional complexity. Sometimes this is necessary, other times it gets in the way. Here is one example. Suppose you want to write a few functions that allow you to set and retrieve values of cookies. In his book, JavaScript: The Definitive Guide David Flanagan encapsulates this functionality in an object. He instantiates a cookie object and then access’s the actual cookies via the properties of this object. The problem with this approach is that an object’s life cycle is tied to a page while a cookie can live a much longer life. Here, the overhead and the extra complexity of wrapping a cookie in an object actually makes things less useful and forces the user to instantiate the object on every page that needs to access the cookie and rehydrate it with the values of the actual cookie.

A simple yet effective approach is Scott Andrew‘s. He simply defines three method’s that do the job. These methods can be called from anywhere. Here is his code copied and pasted from http://www.yourhtmlsource.com/javascript/cookies.html.

function createCookie(name, value, days)

{

  if (days) {

    var date = new Date();

    date.setTime(date.getTime()+(days*24*60*60*1000));

    var expires = "; expires="+date.toGMTString();

  }

  else var expires = "";

  document.cookie = name+"="+value+expires+"; path=/";

}
function readCookie(name)

{

  var ca = document.cookie.split(';');

  var nameEQ = name + "=";

  for(var i=0; i < ca.length; i++) {

    var c = ca[i];

    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces

    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);

  }

  return null;

}
function eraseCookie(name)

{

  createCookie(name, "", -1);

}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: