functions inside or outside jquery document ready

前端 未结 5 1181
迷失自我
迷失自我 2020-11-28 04:17

Up until now I just put all my jQuery goodness inside the $(document).ready() function, including simple functions used in certain user interactions.

B

相关标签:
5条回答
  • 2020-11-28 04:36

    If you're creating a function that needs to be called outside of the scope of the $(document).ready() function, keep it outside of the $(document).ready() function.

    Otherwise keep it internal.

    0 讨论(0)
  • 2020-11-28 04:49

    one advantage of putting those functions inside the document ready function is that they don't pollute your global namespace... with the downside that if you need them somewhere else on the page they won't be available.

    0 讨论(0)
  • 2020-11-28 04:56

    Put it inside so it won't pollute the global namespace. It also ensures a faster resolve of the function name because of JavaScript's scope chains.

    Put it outside if it's a reusable component so you could easily move it in a separate file and call from different contexts.

    Since you already use JQuery, it's worth mentioning, that in your case you may want to define hexvalidate as a JQuery plugin outside and then invoke it inside.

    0 讨论(0)
  • 2020-11-28 04:58

    I don't think you should be using any 'just functions' in the first place. In OOP javascript a "function" usually belongs to one of four distinct types:

    • Constructor or an anonymous 'init' closure - used to construct objects. The only type of function that is allowed to be global
    • Method - function that is a part of some object
    • Utility - inner function of a constructor/method, invisible from outside
    • Constant - a functional constant passed as a parameter

    e.g.

     (function() { <- init closure
    
            function helper1() { <- utility }
    
            globalSomething = {
    
                  foobar: function() { <- method 
                      xyz.replace(/.../, function() { <- constant })
    
                  }
            }
      )()
    

    In your example, 'hexvalidate' is obviously a part of Validator object, which, in turn, can be made a jQuery plugin:

       (function($) {
            $.validate = {
                hexColor: function(color) { ... your code }
                more validators...
            }
         )(jQuery)
    
    0 讨论(0)
  • 2020-11-28 05:00

    If all your functions are only called from within the jQuery(function () { }) block, put them inside it. Otherwise you're needlessly polluting the global namespace, which may lead to conflicts down the road.

    Only declare functions globally that are also used by code in other scopes.

    0 讨论(0)
提交回复
热议问题