logo头像
Snippet 博客主题

extend 深度复制

本文于1349天之前发表,文中内容可能已经过时。

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
let hasOwn = Object.prototype.hasOwnProperty
let toString = Object.prototype.toString
let class2type = {}
let type = function (obj) {
return obj === null ? String(obj) : class2type[ toString.call(obj) ] || 'object'
}
let isWindow = function (obj) {
return obj && typeof obj === 'object' && 'setInterval' in obj
}
/**
* 判断是否是纯对象
*/
let isPlainObject = function (obj) {
if (!obj || type(obj) !== 'object' || obj.nodeType || isWindow(obj)) {
return false
}
if (obj.constructor && !hasOwn.call(obj, 'constructor') && !hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) {
return false
}
var key
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key)
}
/**
* 判断是否是纯函数
*/
let isFunction = function (obj) {
return type(obj) === 'function'
}
/**
* 判断是否是纯数组
*/
let isArray = Array.isArray || function (obj) {
return type(obj) === 'array'
}
/**
* 对象的深copy
* 参数1: 布尔值 可以省略 判断是否深度拷贝,默认false
* example extend(false, {a: {name: '张三'}}, {b: {name: '李四'}})
*/
export default function extend () {
let options
let name
let src
let copy
let copyIsArray
let clone
let target = arguments[0] || {}
let i = 1
let length = arguments.length
let deep = false
if (typeof target === 'boolean') {
deep = target
target = arguments[1] || {}
i = 2
}
if (typeof target !== 'object' && !isFunction(target)) {
target = {}
}
if (length === i) {
target = this
--i
}
for (; i < length; i++) {
if ((options = arguments[ i ]) !== null) {
for (name in options) {
src = target[name]
copy = options[name]
if (target === copy) {
continue
}
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false
clone = src && isArray(src) ? src : []
} else {
clone = src && isPlainObject(src) ? src : {}
}
target[name] = extend(deep, clone, copy)
} else if (copy !== undefined) {
target[name] = copy
}
}
}
}
return target
}