JQuery.extend()与JQuery.fn.extend()的区别

JQuery.extend()与JQuery.fn.extend()


本篇文章概要:

  • JQuery.extend(),JQuery.fn.extend()的源码分析
  • JQuery.extend()的使用
  • JQuery.fn.extend()的使用

JQuery.extend(),JQuery.fn.extend()的源码分析

废话少说,直接上源码

由此可见:jQuery.fn $.fn 就是JQuery构造函数的原型对象

jQuery.fn = jQuery.prototype = {
    
}

JQueryJQuery.fn,也就是说 JQuery本身 和 JQuery的原型 上都有extend函数,

target = this;

target[ name ] = copy;

上面两行代码说明拓展的函数都添加到this上,
JQuery.extend的this指向JQuery本身,
JQuery.fn.extend的this指向JQuery实例对象,也就是$(‘div’)

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;

		// Skip the boolean and the target
		target = arguments[ i ] || {};
		i++;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !isFunction( target ) ) {
		target = {};
	}

	// Extend jQuery itself if only one argument is passed
	if ( i === length ) {
		target = this;
		i--;
	}

	for ( ; i < length; i++ ) {

		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) {

			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = Array.isArray( copy ) ) ) ) {

					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && Array.isArray( src ) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject( src ) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

JQuery.extend()的使用

jQuery.extend(object):拓展JQuery对象本身,用来在jQuery命名空间上增加新函数。
一般用来添加工具函数

举个栗子:

jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});

jQuery.min(2,3); // => 2
jQuery.max(4,5); // => 5

JQuery.fn.extend()的使用

扩展 jQuery 元素集来提供新的方法(通常用来制作插件)。
jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();

方法是添加在原型上,只能实例对象调用,JQuery自身不能调用,
所以一般是插件,而不是一般的工具方法,
针对的对象是$()对象。

你可能感兴趣的:(前端)