重写JS方法
2021-11-24 本文已影响0人
guoXuJianShu
1. 浅拷贝
function clone(origin, target) {
let tar = target || {}
for (const key in origin) {
tar[key] = origin[key]
}
return tar
}
2. 深拷贝
// 1. 遍历对象中每一个属性
// 2. 先排除原型链上的属性
// 3. 在判断遍历的当前属性是不是引用值
// 4. 如果不是引用值,就将当前属性和值赋值给target
// 5. 如果是引用值,先判断是数组还是对象,
// 如果是数组,就将当前属性和[]赋值给target
// 如果是对象,就将当前属性和{}赋值给target
// 在递归
function deepClone (origin, target = {}) {
for (let key in origin) {
if (origin.hasOwnProperty(key)) {
if (typeof(origin[key]) === 'object' && typeof(origin[key]) !== null) {
if ({}.toString.call(origin[key]) === '[object Array]') {
target[key] = []
} else {
target[key] = {}
}
deepClone(origin[key], target[key])
} else {
target[key] = origin[key]
}
}
}
return target
}
/**
* @description 深度克隆
* @param {object} obj 需要深度克隆的对象
* @returns {*} 克隆后的对象或者原值(不是对象)
*/
function deepClone(obj) {
// 对常见的“非”值,直接返回原来值
if ([null, undefined, NaN, false].includes(obj)) return obj
if (typeof obj !== 'object' && typeof obj !== 'function') {
// 原始类型直接返回
return obj
}
const o = test.array(obj) ? [] : {}
for (const i in obj) {
if (obj.hasOwnProperty(i)) {
o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
}
}
return o
}
对象深度合并
/**
* @description JS对象深度合并
* @param {object} target 需要拷贝的对象
* @param {object} source 拷贝的来源对象
* @returns {object|boolean} 深度合并后的对象或者false(入参有不是对象)
*/
function deepMerge(target = {}, source = {}) {
target = deepClone(target)
if (typeof target !== 'object' || typeof source !== 'object') return false
for (const prop in source) {
if (!source.hasOwnProperty(prop)) continue
if (prop in target) {
if (typeof target[prop] !== 'object') {
target[prop] = source[prop]
} else if (typeof source[prop] !== 'object') {
target[prop] = source[prop]
} else if (target[prop].concat && source[prop].concat) {
target[prop] = target[prop].concat(source[prop])
} else {
target[prop] = deepMerge(target[prop], source[prop])
}
} else {
target[prop] = source[prop]
}
}
return target
}
3. 重写promise
function MyPromise(executor) {
this.status = 'pending'
this.data = undefined
this.reason = undefined
this.resolvedCallbacks = []
this.rejectedCallbacks = []
let resolve = (value) => {
if (this.status === 'pending') {
this.status = 'fulfilled'
this.data = value
this.resolvedCallbacks.forEach(fn => fn(this.data))
}
}
let reject = (reason) => {
if (this.status === 'pending') {
this.status = 'rejected'
this.reason = reason
this.rejectedCallbacks.forEach(fn => fn(this.reason))
}
}
executor(resolve, reject)
}
MyPromise.prototype.then = function(onResolved, onRejected) {
if (this.status === 'pending') {
this.resolvedCallbacks.push(onResolved)
this.rejectedCallbacks.push(onRejected)
}
// 如果是成功状态直接成功的回调函数
if (this.status === 'fulfilled') {
onResolved(this.data)
}
// 如果是失败状态直接调失败的回调函数
if (this.status === 'rejected') {
onRejected(this.reason)
}
}