29 Jun 2009

Playing with Javascript namespaces

I often have javascript colisions when using different ajax frameworks in the same page...
So I was wondering how namespaces works in javascript...

I found the beginning of an explanation in this article: 24-javascript-best-practices-for-beginners

But there doesn't seems to be any real convention about this looking at this blog and the associated comments: JavaScript Namespaces

I tried various versions, it seems to me the simplest/shortest is the best... my 2 cents

// simple namespace like ExtJs
Project = {
name : "joe"
}

// a bit like java package but with underscore
com_company_project = {
name : "joe"
}


// java package style
com = {
company : {
project : {
name : "joe"
}
}
}

// Yahoo style
// var X = YAHOO.util.Dom.get();
PROJECT = {
core : {
Functionality : {
name : "joe"
}
}
}

function display() {
console.log("namespaces");
console.log("root: " + Project.name);
console.log("unscore: " + com_company_project.name);
console.log("nested: " + com.company.project.name);
console.log("yahoo: " + PROJECT.core.Functionality.name);
}


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Javascript</title>
<script type="text/javascript" src="namespaces.js"></script>
</head>
<body>
<h1>Javascript</h1>
<h2>consoleLog</h2>
<div id="consoleLog">
<input type="submit" value="console.log" onclick="javascript:display();"/>
</div>
</body>
</html>


No comments: