类型监测函数:
let isType = type => obj => {
return Object.prototype.toString.call(obj) === `[object ${type}]`
}
Object.assign简单实现(浅拷贝):
if (typeof Object.shallowClone !== 'function') {
Object.defineProperty(Object, 'shallowCopy', {
value: function (target) {
if (!isType('Object')(target) && !isType('Array')(target)) {
throw new TypeError('this target should be a object')
}
let to = Object(target)
for (let index = 1; index < arguments.length; index++) {
let nextSource = arguments[index]
if (nextSource !== null) {
for (let nextKey in nextSource) {
to[nextKey] = nextSource[nextKey]
}
}
}
return to
},
configurable: true,
writable: true
})
}
深拷贝简单实现(数组、对象):
if (typeof Object.deepClone !== 'function') {
Object.defineProperty(Object, 'deepClone', {
value: function (target) {
console.log(target)
if (!isType('Object')(target) && !isType('Array')(target)) {
throw new TypeError('this target should be a object')
}
let to = Object(target)
console.log(to)
console.log(arguments)
for (let index = 1; index < arguments.length; index++) {
let nextSource = arguments[index]
getDeepClone(nextSource, to)
}
return to
},
configurable: true,
writable: true
})
}
function getDeepClone (params, target) {
let nextSource = params
if (params !== null) {
for (let nextKey in nextSource) {
if (!isType('Object')(nextSource[nextKey]) && !isType('Array')(nextSource[nextKey])) {
target[nextKey] = nextSource[nextKey]
} else {
if (isType('Object')(nextSource[nextKey])) {
getDeepClone(nextSource[nextKey], target[nextKey] = {})
} else if (isType('Array')(nextSource[nextKey])) {
getDeepClone(nextSource[nextKey], target[nextKey] = [])
}
}
}
}
}