jQuery插件Vs中的私有函数.在每个循环之外

Pab*_*blo 3 javascript jquery jquery-plugins

在下面的示例中,在jQuery插件中包含私有函数有什么区别:

循环外:

    (function( $ ){
      var defaults = {};

      $.fn.cmFlex = function(opts) {

        this.each(function() {
            var $this = $(this);
            //Element specific options
            var o = $.extend({}, defaults, opts);

            //Code here
        });

        function f1(){....
        function f3(){....
        function f2(){....

      };
    })( jQuery );
Run Code Online (Sandbox Code Playgroud)

循环内部:

    (function( $ ){
      var defaults = {};

      $.fn.cmFlex = function(opts) {

        this.each(function() {
            var $this = $(this);
            //Element specific options
            var o = $.extend({}, defaults, opts);

            function f1(){....
            function f3(){....
            function f2(){....
        });     


      };
    })( jQuery );
Run Code Online (Sandbox Code Playgroud)

在循环中包含函数的优点是我将能够访问$ this变量以及f1()f2()f3()中的元素特定选项,这有什么缺点吗?

Jua*_*des 9

始终遵循为您的所有代码提供最低权限的概念.如果没有其他代码需要引用这些函数,则无需在外部定义它们,并且更改这些函数更简单,因为您可以保证它们不会在循环内的任何其他地方使用.

如果f1,f2,f3需要访问循环函数中的闭包变量,则无论如何都必须在函数中定义它们.

不过有一点需要注意.在函数中定义它们需要在每次运行循环函数时创建一个新的闭包.根据环路的紧密程度,它可能会影响性能.我的观点是:过早优化是不好的,但请记住.

仅供参考:这是另一种方法(如果你不需要闭包变量),它可以避免为循环的每次迭代创建闭包.它看起来有点复杂,所以它不适合胆小的人

(function( $ ){
  var defaults = {};

  $.fn.cmFlex = function(opts) {

    this.each((function() {
        function f1(){}
        function f3(){}
        function f2(){}
        // This is the method that will be called for each iteration of the loop. It now
        // has access to f1,f2,f3 but doesn't need to create a closure for each iteration.  
        return function() {
          var $this = $(this);
          //Element specific options
          var o = $.extend({}, defaults, opts);
          f1();
          f2();
          f3();
        };
    })());
  };
})( jQuery );
Run Code Online (Sandbox Code Playgroud)