一、$.fn.method()=function(){}和$.fn.extend({})的比較
jQuery.fn === jQuery.prototype
1.$.fn.method()=function(){}的調用把方法擴展到了對象的prototype上,所以實例化一個jQuery對象的時候,它就具有了這些方法。
比如:
$.fn.myExtension = function(){ var currentjQueryObject = this; //work with currentObject return this;//you can include this if you would like to support chaining };
$.fn.blueBorder = function(){ this.each(function(){ $(this).css("border","solid blue 2px"); }); return this; }; $.fn.blueText = function(){ this.each(function(){ $(this).css("color","blue"); }); return this; };
由於有return this,所以支持鏈式,在調用的時候可以這樣寫:$('.blue').blueBorder().blueText();
2.$.fn.extend({}) 是對$.fn.method()=function(){}的擴展,它可以定義多個方法:
$.fn.extend({ a: function() { }, b: function() { } });
等效於:
$.fn.a = function() { }; $.fn.b = function() { };
二、$.extend({}) ,為jQuery類添加方法,可以理解為擴展靜態方法
$.extend({ abc: function(){ alert('abc'); } });
usage: $.abc()
. (No selector required like $.ajax()
.)
原文:https://www.cnblogs.com/qicao/p/8568158.html