jquery 手册
Ajax
属性(Attributes)
回调对象(Callbacks ..
核心(Core)
CSS
数据(Data)
延迟对象(Deferred o ..
尺寸(Dimensions)
效果(Effects)
事件(Events)
表单(Forms)
文档操作(Manipulati ..
杂项(Miscellaneou ..
位置(Offset)
插件编写(Plugin Aut ..
属性(Properties)
选择器(Selectors)
遍历(Traversing)
工具(Utilities)

Returns: jQueryjQuery jQuery.sub( )

描述:创建一个jQuery的新拷贝,修改其属性和方法不会影响到原来的jQuery对象.
  • version added: 1.5
  • jQuery.sub( )

这个方法的应用场景可以通过下面的例子来了解.

Examples:

例子:

添加一个方法到jQuery sub对象,该对象不会暴露到外部:
(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方法来提供新功能.
(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'.

例子:

创建一个插件,它返回插件的具体方法.
(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!
});