jQuery extend()详解及简单实例


Posted in jQuery onMay 06, 2017

jQuery extend()详解及简单实例

使用jQuery的时候会发现,jQuery中有的函数是这样使用的:

$.get(); 
$.post(); 
$.getJSON();

有些函数是这样使用的:

$('div').css(); 
$('ul').find('li');

有些函数是这样使用的:

$('li').each(callback); 
$.each(lis,callback);

这里涉及到两个概念:工具方法与实例方法。通常我们说的工具方法是指无需实例化就可以调用的函数,如第一段代码;实例方法是必须实例化对象以后才可以调用的函数,如第二段代码。jQuery中很多方法既是实例方法也是工具方法,只是调用方式略有不同,如第三段代码。为了更清晰解释JavaScript中的工具方法与实例方法,进行如下测试。

functionA(){ 
     
  } 
  A.prototype.fun_p=function(){console.log("prototpye");}; 
  A.fun_c=function(){console.log("constructor");}; 
  var a=new A(); 
  A.fun_p();//A.fun_p is not a function 
  A.fun_c();//constructor 
  a.fun_p();//prototpye 
  a.fun_c();//a.fun_c is not a function

通过以上测试可以得出结论,在原型中定义的是实例方法,在构造函数中直接添加的是工具方法;实例方法不能由构造函数调用,同理,工具方法也不能由实例调用。

当然实例方法不仅可以在原型中定义,有以下三种定义方法:

functionA(){ 
    this.fun_f=function(){ 
        console.log("Iam in the constructor"); 
    }; 
} 
A.prototype.fun_p=function(){ 
    console.log("Iam in the prototype"); 
}; 
var a=newA(); 
a.fun_f();//Iam in the constructor 
a.fun_i=function(){ 
    console.log("Iam in the instance"); 
}; 
a.fun_i();//Iam in the instance 
a.fun_p();//Iam in the prototype

这三种方式的优先级为:直接定义在实例上的变量的优先级要高于定义在“this”上的,而定义在“this”上的又高于 prototype定义的变量。即直接定义在实例上的变量会覆盖定义在“this”上和prototype定义的变量,定义在“this”上的会覆盖prototype定义的变量。

下面看jQuery中extend()方法源码:

jQuery.extend = jQuery.fn.extend = function() { 
    var options,name, src, copy, copyIsArray, clone, 
        target= arguments[0] || {}, 
        i =1, 
        length= arguments.length, 
        deep= false; 
    // Handle adeep copy situation 
    if ( typeoftarget === "boolean" ) { 
        deep= target; 
        //Skip the boolean and the target 
        target= arguments[ i ] || {}; 
        i++; 
    } 
    // Handlecase when target is a string or something (possible in deep copy) 
    if ( typeoftarget !== "object" && !jQuery.isFunction(target) ) { 
        target= {}; 
    } 
    // ExtendjQuery 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= jQuery.isArray(copy)) ) ) { 
                   if( copyIsArray ) { 
                       copyIsArray= false; 
                       clone= src && jQuery.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; 
                } 
            } 
        } 
    } 
    // Returnthe modified object 
    return target; 
};

(1)首先,jQuery和其原型中extend()方法的实现使用的同一个函数。

(2)当extend()中只有一个参数的时候,是为jQuery对象添加插件。在jQuery上扩展的叫做工具方法,在jQuery.fn(jQuery原型)中扩展的是实例方法,即使在jQuery和原型上扩展相同名字的函数也可以,使用jQuery对象会调用工具方法,使用jQuery()会调用实例方法。

(3)当extend()中有多个参数时,后面的参数都扩展到第一个参数上。

var a={}; 
$.extend(a,{name:"hello"},{age:10}); 
console.log(a);//Object{name: "hello", age: 10}

(4)浅拷贝(默认):   

var a={}; 
varb={name:"hello"}; 
$.extend(a,b); 
console.log(a);//Object{name: "hello"} 
a.name="hi"; 
console.log(b);//Object{name: "hello"}

b不受a影响,但是如果b中一个属性为对象:

var a={}; 
varb={name:{age:10}}; 
$.extend(a,b); 
console.log(a.name);//Object{age: 10} 
a.name.age=20; 
console.log(b.name);//Object{age: 20}

由于浅拷贝无法完成,则b.name会受到a的影响,这时我们往往希望深拷贝。

深拷贝:   

var a={}; 
varb={name:{age:10}}; 
$.extend(true,a,b); 
console.log(a.name);//Object{age: 10} 
a.name.age=20; 
console.log(b.name);//Object{age: 10}

b.name不受a的影响。

var a={name:{job:"Web Develop"}}; 
var b={name:{age:10}}; 
$.extend(true,a,b); 
console.log(a.name);//age: 10 job: "Web Develop"
//b.name没有覆盖a.name.job。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

jQuery 相关文章推荐
jQuery实现的动态文字变化输出效果示例【附演示与demo源码下载】
Mar 24 jQuery
jQuery zTree树插件动态加载实例代码
May 11 jQuery
jQuery插件FusionCharts绘制的2D条状图效果【附demo源码】
May 13 jQuery
jQuery用户头像裁剪插件cropbox.js使用详解
Jun 07 jQuery
jQuery+C#实现参数RSA加密传输功能【附jsencrypt.js下载】
Jun 26 jQuery
基于JQuery的Ajax方法使用详解
Aug 16 jQuery
jQuery实现的简单获取索引功能示例
Jun 04 jQuery
jQuery基于闭包实现的显示与隐藏div功能示例
Jun 09 jQuery
jQuery中ajax请求后台返回json数据并渲染HTML的方法
Aug 08 jQuery
jquery ajax加载数据前台渲染方式 不用for遍历的方法
Aug 09 jQuery
jQuery实现左右两个列表框的内容相互移动功能示例
Jan 27 jQuery
jquery html添加元素/删除元素操作实例详解
May 20 jQuery
jquery仿微信聊天界面
May 06 #jQuery
简单实现jQuery弹幕效果
May 06 #jQuery
jquery实现提示语淡入效果
May 05 #jQuery
Jquery获取radio选中的值
May 05 #jQuery
jQuery实现简单的抽奖游戏
May 05 #jQuery
jquery中each循环的简单回滚操作
May 05 #jQuery
jquery dataTable 获取某行数据
May 05 #jQuery
You might like
利用ThinkPHP内置的ThinkAjax实现异步传输技术的实现方法
2011/12/19 PHP
VBScript版代码高亮
2006/06/26 Javascript
复制本贴标题和地址的js代码
2008/07/01 Javascript
Javascript算符的优先级介绍
2013/03/20 Javascript
用javascript对一个json数组深度赋值示例
2014/07/27 Javascript
js获取时间并实现字符串和时间戳之间的转换
2015/01/05 Javascript
JavaScript实现仿网易通行证表单验证
2015/05/25 Javascript
JavaScript实现为input与textarea自定义hover,focus效果的方法
2015/08/21 Javascript
js中数组结合字符串实现查找(屏蔽广告判断url等)
2016/03/30 Javascript
JavaScript基于对象去除数组重复项的方法
2016/10/09 Javascript
利用React-router+Webpack快速构建react程序
2016/10/27 Javascript
微信小程序-拍照或选择图片并上传文件
2017/01/06 Javascript
Bootstrap Table从零开始
2017/06/30 Javascript
用 Vue.js 递归组件实现可折叠的树形菜单(demo)
2017/12/25 Javascript
OkHttp踩坑随笔为何 response.body().string() 只能调用一次
2018/01/08 Javascript
解决vue-router路由拦截造成死循环问题
2020/08/05 Javascript
[47:20]DAC2018 4.4 淘汰赛 Optic vs Mineski 第一场
2018/04/05 DOTA
[01:03:27]Optic vs VGJ.S 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
Python类的专用方法实例分析
2015/01/09 Python
Python新手实现2048小游戏
2015/03/31 Python
将Django使用的数据库从MySQL迁移到PostgreSQL的教程
2015/04/11 Python
Python读取和处理文件后缀为.sqlite的数据文件(实例讲解)
2017/06/27 Python
python+selenium识别验证码并登录的示例代码
2017/12/21 Python
Python实现扣除个人税后的工资计算器示例
2018/03/26 Python
python文件写入write()的操作
2019/05/14 Python
Flask框架学习笔记之路由和反向路由详解【图文与实例】
2019/08/12 Python
Python正则表达式急速入门(小结)
2019/12/16 Python
Python通过4种方式实现进程数据通信
2020/03/12 Python
Python函数基本使用原理详解
2020/03/19 Python
Django实现前台上传并显示图片功能
2020/05/29 Python
详解python的super()的作用和原理
2020/10/29 Python
超市实习总结自我鉴定
2013/09/19 职场文书
教师纪念9.18事件演讲稿范文
2014/09/14 职场文书
行政申诉状范文
2015/05/20 职场文书
中学政教处工作总结
2015/08/13 职场文书
2019最新版火锅店的创业计划书 !
2019/07/12 职场文书