Why object oriented JavaScript is not always a good idea
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);
}
leave a comment