返回值:jQueryjQuery.sub()

创建一个 jQuery 的副本,可以修改这个 jQuery 副本的属性和方法而不影响原始的 jQuery 对象。

从 jQuery 1.7 开始,不再建议使用该方法。在 jQuery 1.8 中,该方法将会被移到插件中。

以下是两种使用 jQuery.sub() 的具体情况,第一种情况是希望重写 jQuery 的方法,而不想破坏原始的方法。另一种情况是想为 jQuery 插件做进一步的封装或进行基本的命名空间。

注意,jQuery.sub() 并不尝试做任何形式的隔离,因为这不是该方法的本意。所有 jQuery 副本中的方法依然指向原始的 jQuery (例如,依然会通过原始的 jQuery 进行事件绑定和触发,data 也会通过原始的 jQuery 绑定到元素上。Ajax 请求和事件也是通过原始的 jQuery 运行的等等。)。

注意,如果你想使用它进行插件开发,那么你应该优先考虑使用一些像 jQuery UI 小部件工厂之类的,来管理状态和插件方法。以下是一些使用 jQuery UI 小部件工厂创建插件的例子。

上述那些例子非常好的描述了该方法的详细用法。

示例:

向 jQuery 副本中,添加一个不对外暴露的方法:

jQuery 代码:
  (function(){
    var sub$ = jQuery.sub();

    sub$.fn.myCustomMethod = function(){
      return 'just for me';
    };

    sub$(document).ready(function() {
      sub$('body').myCustomMethod() // 'just for me'
    });
  })();
  
  typeof jQuery('body').myCustomMethod // undefined

示例:

重写一些 jQuery 方法,提供新的功能。

jQuery 代码:

(function() {
  var myjQuery = jQuery.sub();

  myjQuery.fn.remove = function() {
    // New functionality: Trigger a remove event
    this.trigger("remove");

    // Be sure to call the original jQuery remove method
    return jQuery.fn.remove.apply( this, arguments );
  };

  myjQuery(function($) {
    $(".menu").click(function() {
      $(this).find(".submenu").remove();
    });

    // A new remove event is now triggered from this copy of jQuery
    $(document).bind("remove", function(e) {
      $(e.target).parent().hide();
    });
  });
})();

// Regular jQuery doesn't trigger a remove event when removing an element
// This functionality is only contained within the modified 'myjQuery'.

示例:

创建一个插件,返回插件的具体方法。

jQuery 代码:

(function() {
  // Create a new copy of jQuery using sub()
  var plugin = jQuery.sub();

  // Extend that copy with the new plugin methods
  plugin.fn.extend({
    open: function() {
      return this.show();
    },
    close: function() {
      return this.hide();
    }
  });

  // Add our plugin to the original jQuery
  jQuery.fn.myplugin = function() {
    this.addClass("plugin");

    // Make sure our plugin returns our special plugin version of jQuery
    return plugin( this );
  };
})();

$(document).ready(function() {
  // Call the plugin, open method now exists
  $('#main').myplugin().open();

  // Note: Calling just $("#main").open() won't work as open doesn't exist!
});