? ? ? ? ? ? ??
類型監(jiān)測(cè)函數(shù):
let isType = type => obj => {
? ? ? return Object.prototype.toString.call(obj) === `[object ${type}]`
?}
Object.assign簡單實(shí)現(xiàn)(淺拷貝):
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
? ? ?})
? ?}
深拷貝簡單實(shí)現(xiàn)(數(shù)組、對(duì)象):
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] = [])
? ? ? ? ? }
? ? ? ? }
? ? }
? }
}