Javascript扩展对象extend实现

Author Avatar
ibcLee 10月 26, 2017

也是一个经典的面试题,$.extend是用于合并对象常用的方法,并且支持深度拷贝。
在实现的时候,我们也要考虑到对象属性是否是引用类型,对于引用类型来说,浅拷贝只是复制了对象的引用,我们在修改合并后对象的属性的时候,相应的原对象属性也会被修改,避免这种情况发生,我们就要考虑深拷贝。这样的话,我们的extend函数就应该有三个参数,下面是具体的实现代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 判断一个属性值是否是对象类型
var isObjFunc = function(name) {
var toString = Object.prototype.toString
return function() {
return toString.call(arguments[0]) === '[object ' + name + ']'
}
}
var isObject = isObjFunc('Object')
var isArray = isObjFunc('Array')
var extend = function() {
var index = 0,isDeep = false,obj,copy,destination,source,i
for(i = arguments.length - 1;i>index;i--) {
destination = arguments[i - 1]
source = arguments[i]
if(isObject(source) || isArray(source)) {
console.log(source)
for(var property in source) {
obj = source[property]
if(isDeep && ( isObject(obj) || isArray(obj) ) ) {
copy = isObject(obj) ? {} : []
var extended = extend(isDeep,copy,obj)
destination[property] = extended
}else {
destination[property] = source[property]
}
}
} else {
destination = source
}
}
return destination
}