Last Updated: 25 Jul 2023
|
Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision Last revision Both sides next revision | ||
front-end-tech:javascript:namespacing-and-aliasing-namespaces-in-javascript [May 12, 2008 08:47 AM] dordal |
front-end-tech:javascript:namespacing-and-aliasing-namespaces-in-javascript [Jul 11, 2023 10:16 PM] 110.249.201.18 removed |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | = Namespacing & Aliasing Namespaces in JavaScript = | ||
+ | |||
+ | Javascript has an //implied global namespace// | ||
+ | |||
+ | To do this, create an object. As a convention, I like to start the name of the object with a $ to indicate it is a namespace. Then declare your functions inside your new namespace. You may even want to declare sub-namespaces to group functions. | ||
+ | |||
+ | <code javascript> | ||
+ | // Make sure the $O namespace exists ($O is a random name; it can be anything) | ||
+ | var $O = window.$O || {}; | ||
+ | |||
+ | // Create a sub-namespace for admin functions | ||
+ | $O.admin = {}; | ||
+ | |||
+ | // create an array in the main $O namespace | ||
+ | $O.usernames = [' | ||
+ | |||
+ | // create a function in the admin sub-namespace, | ||
+ | $O.admin.getUsername = function(arrayIndex) { | ||
+ | | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | **IMPORTANT: | ||
+ | |||
+ | == Aliasing Namespaces == | ||
+ | You can alias other people' | ||
+ | <code javascript> | ||
+ | var $D = YAHOO.util.Dom; | ||
+ | var $E = YAHOO.util.Event; | ||
+ | var $El = YAHOO.util.Element; | ||
+ | var $ = $D.get; | ||
+ | |||
+ | // Now, I can access functions more simply: | ||
+ | $D.getElementsByClassName(' | ||
+ | |||
+ | // Above, I've even aliased YUI's ' | ||
+ | var myElementVar = $(' | ||
+ | </ | ||