$.extend、$.fn.extend

$.extend

1、扩展jQuery静态方法.

$.extend({
  myFun:function(){alert(
'test函数')}   min: function(a, b) { return a < b ? a : b; },   max: function(a, b) { return a > b ? a : b; } }); $.myFun(); $.min(2,3); // 2 $.max(4,5); // 5

2、合并多个对象.

var newcss = jquery.extend(css1,css2)  //newcss就是合并的新对象。
var newcss = jquery.extend({},css1,css2) //newcss就是合并的新对象.而且没有破坏css1的结构。

//用法: jQuery.extend(obj1,obj2,obj3, ..)
var Css1={size: "10px",style: "oblique"}
var Css2={size: "12px",style: "oblique",weight: "bolder"}
$.jQuery.extend(Css1,Css2)
//结果: Css1 = {size: "12px",style: "oblique",weight: "bolder"}

3、深度镶套对象
新的extend()允许你更深度的合并镶套对象

// 以前的 .extend()   
jQuery.extend(   
  { name: “John”, location: { city: “Boston” } },     { last: “Resig”, location: { state: “MA” } }   
);   
//结果:{ name: “John”, last: “Resig”, location: { state: “MA” } }
// 新的更深入的 .extend() jQuery.extend(
  true,   { name: “John”, location: { city: “Boston”, country:”USA”} },   { last: “Smith”, location: { state: “MA”, country:”china”} } ); //结果 { name:“John”, last:“Smith”, location:{city:“Boston”, state:“MA”, country:”china” }}

$.fn.extend(object);

$.fn是指jQuery的命名空间,fn上的成员(方法function及属性property),会对jQuery实例每一个有效。 

jQuery.fn = jQuery.prototype = {

init: function( selector, context ) {//.... 

};

原来 jQuery.fn = jQuery.prototype.

所以,它是对jQuery.prototype进一步得扩展,就是为jQuery类添加“成员函数”。jQuery类的实例可以使用这个“成员函数”。

比如要开发一个插件,做一个特殊的编辑框,当它被点击时,便alert当前编辑框里的内容

$.fn.extend({          
     doAlertWhileClick:function() {            
           $(this).click(function(){                 
                   alert($(this).val());           
            });           
      }       
});       
$("#input1").doAlertWhileClick(); // 页面上为:    

//$("#input1") 为一个jQuery实例,当它调用成员方法 doAlertWhileClick后,便实现了扩展,每次被点击时它会先弹出目前编辑里的内容。

区别:

1、两者调用方式不同:

jQuery.extend()一般由传入的全局函数来调用,主要用来拓展全局函数,如$.init()、$.ajax();

jQuery.fn.extend()一般由具体的实例对象来调用,可用来拓展个选择器,例如$.fn.each();

2、两者的主要功能作用不同:

jQuery.extend(object); 为扩展jQuery类本身,为自身添加新的方法。jQuery.fn.extend(object);给jQuery对象添加方法

3、大部分插件都是用jQuery.fn.extend()

 

原文地址:https://www.cnblogs.com/whatarewords/p/10718607.html