jQuery Plugin Namespacing Functions

后端 未结 4 893
-上瘾入骨i
-上瘾入骨i 2021-02-04 15:20

I\'m creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.

(function($){         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-04 16:20

    As soon as you use $.fn.foo.bar() -- this points to $.fn.foo, which is what you would expect in JavaScript (this being the object that the function is called on.)

    I have noticed in plugins from jQuery UI (like sortable) where you call functions like:

    $(...).sortable("serialize");
    $(...).sortable({options});
    

    If you were doing something like this - you could extend jQuery itself:

    $.foo_plugin = {
      bar: function() {},
      baz: function() {}
    }
    
    $.fn.foo = function(opts) {
      if (opts == 'bar') return $.foo_plugin.bar.call(this);
      if (opts == 'baz') return $.foo_plugin.baz.call(this);
    }
    

提交回复
热议问题