forked from yeyan1996/practical-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assign.js
49 lines (38 loc) · 1.21 KB
/
assign.js
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
"use strict" //启用严格模式在尝试给基本包装类型已定义的下标赋值的时候报错
const isComplexDataType = obj => (typeof obj === 'object' || typeof obj === 'function') && obj !== null
//简单实现ES6的Object.assign
const selfAssign = function (target, ...source) {
if (target == null) throw new TypeError('Cannot convert undefined or null to object')
return source.reduce((acc, cur) => {
isComplexDataType(acc) || (acc = new Object(acc)); //变成一个基本包装类型
if (cur == null) return acc; //source为null,undefined时忽略
// 遍历出Symbol属性和可枚举属性
[...Object.keys(cur), ...Object.getOwnPropertySymbols(cur)].forEach(key => {
acc[key] = cur[key]
})
return acc
}, target)
}
Object.selfAssign || Object.defineProperty(Object, 'selfAssign', {
value: selfAssign,
configurable: true,
enumerable: false,
writable: false
})
let target = {
a: 1,
b: 1
}
let obj1 = {
a: 2,
b: 2,
c: undefined
}
let obj2 = {
a: 3,
b: 3,
[Symbol("a")]: 3,
d: null
}
console.log(Object.selfAssign(target, obj1, obj2))
console.log(Object.selfAssign("abd", null, undefined))