{"id":34,"date":"2009-06-16T15:30:10","date_gmt":"2009-06-16T22:30:10","guid":{"rendered":"http:\/\/adam.yanalunas.com\/blog\/?p=34"},"modified":"2009-06-17T13:49:43","modified_gmt":"2009-06-17T20:49:43","slug":"what-isnt-in-a-name","status":"publish","type":"post","link":"http:\/\/adam.yanalunas.com\/blog\/archives\/34","title":{"rendered":"What isn&#8217;t in a name?"},"content":{"rendered":"<p>If you don&#8217;t already know, polluting the global variable pool is a bad, evil thing in JavaScript land. If you&#8217;re not concerned with overwriting existing code then at least think about protecting your code from being overwritten by keeping it in your own namespace. All you need to create a namespace in JavaScript is an <a href=\"http:\/\/en.wikipedia.org\/wiki\/Object_literal#In_ECMAScript.2FJavaScript\">object literal<\/a>.<\/p>\n<p>Say you&#8217;re tasked with incorporating a third-party widget into your home page. You drop in their <code><script src=\"foo.js\"><\/script><\/code> include but suddenly one of the scripts on your site breaks. You haven&#8217;t changed your code so you assume it&#8217;s the include causing trouble. However, a <a title=\"JSLint, The JavaScript Code Quality Tool\" href=\"http:\/\/www.jslint.com\/\">JSLint<\/a> shows that their syntax checks out fine. Looking through your functions you narrow the misbehaving lines down to the following:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nfunction findElement(el) {\r\n    return document.getElementById(el);\r\n}\r\n\r\nfunction updateNews(content) {\r\n    findElement('news').innerHTML=content;\r\n}\r\n<\/pre>\n<p>That is some horrible code. Worse, that&#8217;s horrible code in the global pool. Cracking open the third-party include you see this:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nupdateNews = function(container,source,freq)\r\n{\r\n    \/\/ Snip....\r\n}\r\n<\/pre>\n<p>My, that function name looks awfully familiar. In fact, it&#8217;s the same as yours. That means your code and the third-party code are fighting in the global variable pool. What&#8217;s a clever programmer to do? Do what works in other languages, of course!<\/p>\n<h2>Time to carve out your own namespace<\/h2>\n<p>This is ridiculously easy if you understand what object literals are and how to self-invoke an anonymous function. Those terms both sound scarier than they are. You simply create an object literal to act as your namespace &#038;#8211 which is a bucket for all your code &#8211; then use anonymous functions to assign functions into it. Keeping with the theme of being a polite player in the global pool also make sure your namespace is either brand new or extends any existing namespace.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar AY = AY || {}; \/\/Don't overwrite existing namespaces\r\nAY.News = function() \/\/A 'News' bucket for all news-related tasks\r\n{\r\n    \/\/The 'var' forces the findElement method \r\n    \/\/into the News scope, not global\r\n    var findElement = function(el)\r\n    {\r\n        return document.getElementById(el);\r\n    }\r\n    \r\n    \/\/Anything in the return becomes publicly accessible, yet \r\n    \/\/is also able to access private methods and variables\r\n    return {\r\n        updateNews: function(content)\r\n        {\r\n            findElement('news').innerHTML = content;\r\n        }\r\n    }\r\n}(); \/\/Self-invoke to make this available immediately\r\nAY.News.updateNews('Hai');\r\n<\/pre>\n<p>What&#8217;s happening here? Well instead of dropping all of your code into the global you can stash it in a single namespace. In my case I&#8217;ve named my namespace as <code>AY<\/code>, after my name. I used all capital letters to signify that this is not a variable or method belonging to any other code. For news-related items I&#8217;ve created a <code>News<\/code> bucket.<\/p>\n<p>Inside of my News bucket there are a few things happening. I&#8217;ve decided that <code>findElement<\/code> should be a private method in my namespace so by prepending it with the <code>var = <\/code> I designate it as existing only inside the <code>AY.News<\/code> namespace. Without a public accessor no outside code can run that method. My return passes an object literal which houses any public methods, in this case the <code>updateNews<\/code> method. Because they are a part of my <code>AY.News<\/code> namespace these public methods can access private methods, which is why the <code>updateNews<\/code> code still works.<\/p>\n<p>Finally, the closing parentheses cause the anonymous function to automatically run, or self-invoke. This action executes the function and, during its execution, hits the return which is what causes the return data to be assigned to <code>AY.News<\/code>. The return is an object literal itself that contains a reference to the &#8220;private&#8221; <code>updateNews<\/code>, which will execute the update. <\/p>\n<p>That&#8217;s it! There&#8217;s no more to it. I&#8217;ll grant that for personal scripts this technique is not absolutely necessary but if you ever want your code to play nicely in another environment it&#8217;s a good practice and makes other programmers less hesitant to use your code. Comments regarding execution of this technique are more than welcome. This is my personal flavor and because of JavaScript&#8217;s flexibility I&#8217;m sure there are some other great techniques out there. Comment away!<\/p>\n<p>Recommended reading:<\/p>\n<ul>\n<li><a href=\"http:\/\/yuiblog.com\/blog\/2007\/06\/12\/module-pattern\/\">A JavaScript Module Pattern<\/a><\/li>\n<li><a href=\"http:\/\/www.klauskomenda.com\/code\/javascript-programming-patterns\/\">JavaScript Programming patterns<\/a><\/li>\n<li><a href=\"http:\/\/www.dustindiaz.com\/namespace-your-javascript\/\">Namespacing Your JavaScript<\/a><\/li>\n<\/ul>\n<p><em>2009-06-17: Reordered and cleaned up copy.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you don&#8217;t already know, polluting the global variable pool is a bad, evil thing in JavaScript land. If you&#8217;re not concerned with overwriting existing code then at least think about protecting your code from being overwritten by keeping it in your own namespace. All you need to create a namespace in JavaScript is an [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[6],"tags":[15,40,16],"_links":{"self":[{"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/posts\/34"}],"collection":[{"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/comments?post=34"}],"version-history":[{"count":12,"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/posts\/34\/revisions"}],"predecessor-version":[{"id":47,"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/posts\/34\/revisions\/47"}],"wp:attachment":[{"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/media?parent=34"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/categories?post=34"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/adam.yanalunas.com\/blog\/wp-json\/wp\/v2\/tags?post=34"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}