码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Patterns 5.2 Declaring Dependencies

时间:2014-06-25 15:15:36      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   java   

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)

JavaScript Patterns 5.2 Declaring Dependencies,布布扣,bubuko.com

JavaScript Patterns 5.2 Declaring Dependencies

标签:des   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/haokaibo/p/Declaring-Dependencies.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!