JavaScript Patterns 5.2 Declaring Dependencies

王朝学院·作者佚名  2016-05-23
窄屏简体版  字體: 小  |  中  |  大  |  超大  

javaScript Patterns 5.2 Declaring Dependencies 2014-06-24 17:48 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑 It’s a good idea to declare the modules your code relies on at the top of your function or module. The declaration involves creating only a local variable and pointing to the desired module.

var myFunction = function() { // dependencies var event = YAHOO.util.Event, dom = YAHOO.util.Dom; // use event and dom variables // for the rest of the function...};

Benefits

• Explicit declaration of dependencies signals to the users of your code the specific script files that they need to make sure are included in the page.

• Upfront declaration at the top of the function makes it easy to find and resolve dependencies.

• Working with a local variable (such as dom) is always faster than working with a global (such as YAHOO) and even faster than working with nested PRoperties of a global variable (such as YAHOO.util.Dom), resulting in better performance. When following this dependency declaration pattern, the global symbol resolution is performed only once in the function. After that the local variable is used, which is much faster.

• Advanced minification tools such as YUICompressor and Google Closure compiler will rename local variables (so event will likely become just one character such as A), resulting in smaller code, but never global variables, because it’s not safe to do so.

References:

Javascript Patterns -by Stoyan Stefanov(O`Reilly)

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航