Using the namespace (Namespace) mode, you can use some JavaScript libraries, such as the global object of YAHOO's role YUI2 library, which can be YAHOO.util.Dom and YAHOO.util.Event gets support for DOM and events in the YUI2 library. Using these modules in a program is declaring a dependency (declaring Dependencies) mode:
var myFunction = function () { //dependencies var event = YAHOO.util.Event, dom = YAHOO.util.Dom; Use event and DOM variables //for the rest of the function ...};
This is a very simple pattern, but it can bring many benefits:
- Explicitly use the modules declared in the global object, so that developers remember to reference these library files;
- A reference to the object is declared at the top of the code block, making the reference easy to find;
- The use of a local variable, can solve the object nested reference when the performance problem;
- Many code-shrinking (minification) tools support shrinking local variable names;
If you do not use this pattern, your code has different effects when it shrinks:
function Test1 () { alert (MYAPP.MODULES.M1); alert (MYAPP.modules.m2); alert (MYAPP.MODULES.M51);} /*minified test1 Body:alert (MYAPP.MODULES.M1); alert (MYAPP.modules.m2); alert (MYAPP.MODULES.M51) */function test2 () { var modules = Myapp.modules; alert (MODULES.M1); alert (modules.m2); alert (MODULES.M51);} /*minified test2 Body:var A=myapp.modules;alert (A.M1); alert (a.m2); alert (A.M51) */
JavaScript Base Object creation Mode declaration dependency mode (023)