模仿JQuery.extend函数,实现JS深拷贝和浅拷贝

这篇博客介绍了如何使用JavaScript模仿JQuery.extend函数,实现对象的深拷贝和浅拷贝。通过定义一个extend方法,并设置是否进行深拷贝的标志,对传入的对象进行遍历,根据不同情况决定是深拷贝还是浅拷贝。最后,博主展示了如何利用这个extend方法为原对象添加新的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    var s={};/原始对象

   //为原对象扩展一个extend方法

    s.extend=function({
        var target=arguments[0]||{},//目标对象
            e=false,//是否进行深拷贝
            h=1,//参数个数
            n= arguments.length,//实际传入的参数个数
            temp;// 临时保存源参数
            
            if(typeof a =='boolean'){
                e=arguments[0];
target=arguments[1]||{};
//skip the boolean and target
                h=2;
            }
            // Handle case when target is a string or something (possible in deep copy) 
            if (typeof target !== "object" && typeof target!== "function") 
                target = {}; 
// extend object itself if only one argument is passed 
            if (n == h) { 
                target = this; 
                --h; 
}

            for(;h<n;h++){
                temp= arguments[h];
                if(typeof temp !=null){
                    for(var t in temp){
   var src = target[t], copy = temp[t];
// Prevent never-ending loop 
                        if (target === copy) 
                           continue; 
                        if(e&&temp[t]&&typeof temp[t]=="object"&&!temp[t].nodeType){
                              //进行深拷贝
                              target[t]=s.extend(e,(src||{}),temp[t]);      
                        }else{
                            //浅拷贝
                            if(temp[t]!=undefined){
                                target[t]=temp[t];  
                            }        
                        }       


                    }  
                } 




            }
            return target;

});

然后通过这个模拟扩展的extend方法,为原来对象增加新的方法

s.extend(s,{

   test1:function(){

     alert('this is test1');

   },

  test2:function(){

    alert('this is test2');

  }

});

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值