jQuery的$.extend()、$.fn和$.fn.extend()

最近学习jQuery,想开发插件,看了其他人的博客,记录一下。
jQuery的编码规则:

  1. 所有的新方法都附加在jQuery.fn对象上
  2. 所有的新功能都附加在jQuery对象上

jQuery中的类及实例:
利用选择器选中的元素或元素集合就是一个jQuery对象:
$(“#test″) 会生成一个 jQuery类的实例。

jQuery.extend(object)

  1. 为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
  1. Object jQuery.extend( target, object1, [objectN])
    用一个或多个其他对象来扩展一个对象,返回被扩展的对象
var settings = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
jQuery.extend(settings, options); 

结果:settings == { validate: true, limit: 5, name: "bar" }

对jQuery.prototype进得扩展,就是为jQuery类添加“成员函数”。jQuery类的实例可以使用这个“成员函数”。
比如我们要开发一个插件,做一个使用脚本控制复选框的选中状态。可以这么做:

$(function () { 
	$.fn.extend({
		check: function() {
			return this.each(function() {
				this.checked = true;
			});
		},
		uncheck: function() {
			return this.each(function() {
				this.checked = false;
			});
		}
	});
	// 使用新创建的.check() 方法
	$( "input[type='checkbox']" ).check();
})

$( "input[type='checkbox']" )是jQuery的实例,当调用check时,便实现了复选框的选中状态。

$.fn

jQuery.fn.extend = jQuery.prototype.extend可以拓展一个对象到jQuery的 prototype里去

(function($){
	// $.fn.tooltip=function(options){
	// 	alert(options);
	// };
	//等价于
	var tooltip={
		test:function(options){
			console.log("tooltip");
		}
	};
	// $.fn.extend(tooltip) = $.prototype.extend(tooltip)=$.fn.tooltip;
	$.fn.tooltip=tooltip;
})(jQuery);
$('p').tooltip.test();
原文地址:https://www.cnblogs.com/AlexanderZhao/p/12572077.html