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 ajax动态新增节点无法触发点击事件的问题
May 24 jQuery
jquery实现一个全局计时器(商城可用)
Jun 30 jQuery
jquery鼠标悬停导航下划线滑出效果
Sep 29 jQuery
jQuery中ajax获取数据赋值给页面的实例
Dec 31 jQuery
jquery在启动页面时,自动加载数据的实例
Jan 22 jQuery
jquery的 filter()方法使用教程
Mar 22 jQuery
jQuery插件实现的日历功能示例【附源码下载】
Sep 07 jQuery
JQuery获取元素尺寸、位置及页面滚动事件应用示例
May 14 jQuery
如何用webpack4.0撸单页/多页脚手架 (jquery, react, vue, typescript)
Jun 18 jQuery
jQuery实现checkbox全选、反选及删除等操作的方法详解
Aug 02 jQuery
jQuery提示框插件SweetAlert用法分析
Aug 05 jQuery
基于JQuery实现页面定时弹出广告
May 08 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
php SQL防注入代码集合
2008/04/25 PHP
php实现文件编码批量转换
2014/03/10 PHP
linux下实现定时执行php脚本
2015/02/13 PHP
php简单备份与还原MySql的方法
2016/05/09 PHP
Laravel 的数据库迁移的方法
2017/07/31 PHP
在b/s开发中经常用到的javaScript技术
2006/08/23 Javascript
utf8的编码算法 转载
2006/12/27 Javascript
js实现的仿新浪微博完美的时间组件升级版
2011/12/20 Javascript
利用百度地图JSAPI生成h7n9禽流感分布图实现代码
2013/04/15 Javascript
jquery+css3打造一款ajax分页插件(自写)
2014/06/18 Javascript
点击标签切换和自动切换DIV选项卡
2014/08/10 Javascript
Javascript学习笔记之函数篇(四):arguments 对象
2014/11/23 Javascript
解决jquery插件:TypeError:$.browser is undefined报错的方法
2015/11/21 Javascript
js中string和number类型互转换技巧(分享)
2016/11/28 Javascript
Bootstrap滚动监听组件scrollspy.js使用方法详解
2017/07/20 Javascript
认识jQuery的Promise的具体使用方法
2017/10/10 jQuery
jquery.onoff实现简单的开关按钮功能(推荐)
2018/05/24 jQuery
layer弹窗在键盘按回车将反复刷新的实现方法
2019/09/25 Javascript
JavaScript实现秒杀时钟倒计时
2019/09/29 Javascript
Vue根据条件添加click事件的方式
2019/11/09 Javascript
JavaScript自定义超时API代码实例
2020/04/30 Javascript
利用Python脚本在Nginx和uwsgi上部署MoinMoin的教程
2015/05/05 Python
python开发之str.format()用法实例分析
2016/02/22 Python
python遍历序列enumerate函数浅析
2017/10/17 Python
python如何派生内置不可变类型并修改实例化行为
2018/03/21 Python
python顺序的读取文件夹下名称有序的文件方法
2018/07/11 Python
Python 用三行代码提取PDF表格数据
2019/10/13 Python
python+django+selenium搭建简易自动化测试
2020/08/19 Python
结合CSS3的新特性来总结垂直居中的实现方法
2016/05/30 HTML / CSS
BookOutlet加拿大:在网上书店购买廉价折扣图书和小说
2018/10/05 全球购物
波兰运动鞋网上商店:Distance.pl
2020/07/30 全球购物
毕业生个人求职的自我评价
2013/10/28 职场文书
节约用电标语
2014/06/17 职场文书
荒岛余生观后感
2015/06/09 职场文书
《我在为谁工作》:工作的质量往往决定生活的质量
2019/12/27 职场文书
Requests什么的通通爬不了的Python超强反爬虫方案!
2021/05/20 Python