import isType from './isType'; import isPlainObject from './isPlainObject'; /** * 拷贝对象 * * @export * @param {Object} target 默认对象(如果为boolean的时候flase为浅拷贝,true为深拷贝,默认为深拷贝) * @param {Object} args 被拷贝的对象 * @returns {Object} target */ function extend( target: boolean, source: T, source1: U, source2: V, source3: W): T & U & V & W; function extend( target: boolean, source: T, source1: U, source2: V): T & U & V; function extend(target: boolean, source: T, source1: U): T & U; function extend(target: boolean, ...args: T[]): T; function extend( source: T, source1: U, source2: V, source3: W): T & U & V & W; function extend(source: T, source1: U, source2: V): T & U & V; function extend(source: T, source1: U): T & U; function extend(target: boolean, source: T): T; function extend(...args: T[]): T; function extend (...args: any[]): any { let isDeep = true; let target: any; if (args instanceof Array) { target = args.slice(0, 1)[0]; } if (typeof target === 'boolean') { isDeep = target; args.splice(0, 1); if (!isDeep) { target = args.splice(0, 1)[0]; } } if (args && args.length < 1) { return typeof target === 'boolean' ? args[1] : target; } if (isDeep) { target = null; } for (let i = 0; i < args.length; i++) { let source = args[i]; if (source instanceof Object) { if (isDeep) { if (!target || !(target instanceof Object)) { target = (source instanceof Array) ? [] : {}; } for (const key in source) { if (source.hasOwnProperty(key)) { const sourceItem = source[key]; if (isObjectAndArray(sourceItem)) { let children: any = isObjectAndArray(target[key]) && target[key] || ((sourceItem instanceof Array) ? [] : {}); target[key] = extend(children, sourceItem); } else { if (typeof sourceItem !== 'undefined') { target[key] = sourceItem; } else if (typeof target[key] !== 'undefined') { target[key] = sourceItem; } } } } } else { if (!target || !(target instanceof Object)) { target = source; } else { target = Object.assign(target, source); } } } } return target; /** * 判断是否为对象 * * @param {*} obj * @returns */ function isObjectAndArray (obj: any): boolean { // return obj && (isType(obj, 'Array') || isType(obj, 'Object') && (!obj.constructor || obj.constructor === Object)) || false; return obj && (isType(obj, 'Array') || isPlainObject(obj)) || false; } } export default extend;