jquery源码之extend

本文深入解析了 jQuery 中的 extend 方法实现原理,通过示例详细解释了如何使用此方法进行对象扩展,包括浅拷贝和深拷贝的区别及应用场景。

jquery的作者是真tm牛逼

jQuery.extend = jQuery.fn.extend = function() {//jQuery.fn = jQuery.prototype,扩展实例方法
	//$.extend({a:(x)=>{console.log(x)}},b:function(){console.log(a)}})
	//这是扩展工具方法,挂载在原型下面,和c#的上次和卢工讨论的一样
	//$.fn.extend({a:(x)=>{console.log(x)}},b:function(){console.log(a)})
	//调用是必须用$().a(1),这样的方法来调,因为这是实例方法
	//$.extend(); ->this ->$
	//$.fn.extend(); ->this ->$.fn
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	if ( length === i ) {
		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 	防止循环引用a={};$.extend(a,{x:a});
				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;
				}
			}
		}
	}

	// Return the modified object
	return target;
};
复制代码
obj={a:{x:12},b:2}
$(true,obj,{a:{x:[1,5]}})
target=obj={a:1,b:2};
i=2;
options={a:{x:[1,5]}}
src=target['a']={x:12};
copy={x:[1,5]};
obj[ 'a' ] = jQuery.extend( true, {x:12,y:6}, {x:[1,5]} );//={x:[1,5],y:6}
    target={x:12,y:6};
    i=2;
    options={x:[1,5]}
    src=12;
    copy=[1,5];
    clone=[];
    targer['x']=$.extend(true,[],[1,5])//...=[1,5]
        target=[];
        i=2;
        options=[1,5];
        src=[][0];                   src=[][1];
        copy=[1,5][0]=1;        copy=[1,5][1]=5;
        target[0]=copy=1;       target[1]=copy=5;
        return target=[0,1]
    return target={x:[1,5]}
return 

复制代码

转载于:https://juejin.im/post/5c962d996fb9a0710d65d907

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值