zepto的extend
类型判断
var class2type = {},toString = class2type.toString,$={};
//判断类型
function type(obj) {
return obj == null ? String(obj) : class2type[toString.call(obj)] || "object"
}
//对象
function isObject(obj) {
return type(obj) == "object"
}
//字面量对象
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
function isArray(arr){
return Array.isArray(arr) || arr instanceof Array
}
zepto.extend
![](http://upload-images.jianshu.io/upload_images/2963329-5ccc2a0dfe1c601f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/488/format/webp)
3
zepto中的扩展,我们可以看到,首先是定义了一个extend函数,这个在内部使用的函数有三个参数target,source,deep。target是将被扩展的对象,source是扩展的对象,deep代表是否深度扩展。那么就直接看第三个参数了。
我们可以看到,在extend函数中,即使使用了深度扩展,也会通过递归函数来重新扩展,最后都会是targte[key]=source[key]
,而区别是:
//test1
var test1 = {
name:"a",
item:{
name:"b",
nickname:"c"
}
};
//简单扩展
extend(test1,{name:"a",item:{name:"b",item:{name:"c"}}});
console.log(test1);
![](http://upload-images.jianshu.io/upload_images/2963329-8955bc2c8acc3f98.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/415/format/webp)
4
可以看到,在没有使用deep时,会直接扩展对象的第一层属性,并直接覆盖。但如果使用了deep:
//深度扩展
extend(test1,{name:"a",item:{name:"b",item:{name:"c"}}},true);
console.log(test1);
![](http://upload-images.jianshu.io/upload_images/2963329-a37b1f8385be3dbd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/309/format/webp)
5
现在扩展对象时就不会修改原对象中不对应的值。
然后是$.extend,这个是可以在外部使用的扩展函数,直接在$对象上定义的,zepto的插件扩展可以不需要通过$.extend扩展到zepto对象里,因为zepto的
dom.__proto__ = $.fn,zepto.Z.prototype = $.fn
,且返回的是$。所以我们可以看见在zepto其他的模块里,给zepto添加动态方法时,是这样直接扩展的:![](http://upload-images.jianshu.io/upload_images/2963329-3b3930a27efd14ef.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/755/format/webp)
6
回到$.extend函数,这里在内部使用arguments,所以该函数是不限参数的,如果想深度扩展,只需要把首个参数设为true。首先是简单扩展的:
var test2 = $.extend(test1,{name:"a",item:{name:"b",item:{name:"c"}}},{name:"d"});
console.log(test2);
![](http://upload-images.jianshu.io/upload_images/2963329-36f171c09b69053f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/326/format/webp)
7
深度扩展:
var test2 = $.extend(true,test1,{name:"a",item:{name:"b",item:{name:"c"}}},{name:"d",item:{name:"e"}});
console.log(test2);
链接:https://www.jianshu.com/p/bdffa1468ed3