创建一个jQuery插件:关于函数可见性的最佳实践?

mar*_*cgg 11 javascript jquery jquery-plugins

我正在创建一个jQuery插件.到目前为止它工作正常,但我对我做事的方式有疑问:

jQuery.fn.myMethod = function() {
  return this.each(function(){
    MyScope.doSomething(jQuery(this).attr("id"));
  });
};

var MyScope = {

  // The functions contained in MyScope are extremely linked to the logic 
  // of this plugin and it wouldn't make a lot of sense to extract them

  doSomething: function(id){
    // something
    doSomethingElse(23);
    // some more code
    doSomethingElse(55);
  },

  doSomethingElse: function(someInt){
    // some code 
  }
};
Run Code Online (Sandbox Code Playgroud)

我使用MyScope存储我的所有"私人"功能.我不希望用户能够去$("p").doSomething(),但我确实需要使用它们.

我可以移动myMethod函数中的所有内容,但它会创建一个100行长的函数,人们会讨厌它.

在这种情况下,最佳做法是什么?关于这个,有没有很棒的教程?

Nic*_*ver 18

您可以封装您的函数以执行您想要的操作,如下所示:

jQuery.fn.myMethod = function() {
  return this.each(function(){
    doSomething(jQuery(this).attr("id"));
  });        
  function doSomething(id){
    //do something
  }
  function doSomethingElse(){
    // some code
  }
};
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看快速演示

"我可以在myMethod函数中移动所有内容,但它会创建一个100行长的函数,人们会讨厌它." .... 为什么?

代码必须在某个地方定义,如果你不希望它可以从外部访问,有几种方法,但我不明白为什么有人会不喜欢你这样做.这一切都与范围和你想要的东西有关,只要你没有多次宣布并且只露出你想要的东西,我就没有看到任何问题.

声明它有几种风格,有些具有相同的效果,我给出的选项是众多的一种,但放置内部myMethod是一种非常合理的方法.


更完整,这是另一种选择:

(function($) { 
    function doSomething(id){
      //do something, e.g:  doSomethingElse('bob');
    }
    function doSomethingElse(str){
      //some code
    }
    $.fn.myMethod = function() {
      return this.each(function(){
        doSomething(jQuery(this).attr("id"));
      });   
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

另一个:

(function($) { 
    var me = {
        doSomething: function(id){
         //do something, e.g:  this.doSomethingElse('bob');
        },
        doSomethingElse: function(str){
          //some code
        }
    };
    $.fn.myMethod = function() {
      return this.each(function(){
        me.doSomething(jQuery(this).attr("id"));
      });   
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

相关文章:


Tim*_*own 6

使用大型函数创建新范围没有任何问题.以下保持doSomethingdoSomethingElse私有,并避免为每次调用定义new doSomethingdoSomethingElse函数,myMethod如果你放入doSomethingdoSomethingElse内部myMethod的定义会发生这种情况.

(function() {
  function doSomething(id) {
    // Something
  }

  function doSomethingElse() {
    // Something else
  }

  jQuery.fn.myMethod = function() {
    return this.each(function(){
      doSomething(this.id);
    });
  };
})();
Run Code Online (Sandbox Code Playgroud)