const obj1 = {
a: 1,
b: 2,
c: {
x: 3,
y: 4,
}
}
const obj2 = deepClone(obj1)
obj2.c.x = 4
console.log(obj2)
console.log(obj1)
// 深拷贝
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj == null) {
return obj
}
const result = Array.isArray(obj) ? [] : {}
for (let key in obj) {
result[key] = deepClone(obj[key])
}
return result
}
// 深度比较
function isObject(obj) {
return typeof obj === 'object' && obj !== null
}
function isEqual(obj1, obj2) {
if (!isObject(obj1) || !isObject(obj2)) {
return obj1 === obj2
}
if (obj1 === obj2) return true
const obj1Keys = Object.keys(obj1)
const obj2Keys = Object.keys(obj2)
if (obj1Keys.length !== obj2Keys.length) return false
for(let key of obj1Keys) {
const res = isEqual(obj1[key], obj2[key])
if (!res) return false
}
return true
}
console.log(isEqual({a:1, b: {c: 1}}, {a: 1, b: {c: 1}}))
// 手写bind
Function.prototype.bind1 = function() {
const args = Array.prototype.slice.call(arguments)
const t = args.shift()
this.apply(t, args)
}
function fn(a,b,c) {
console.log('this', this)
console.log(a,b,c)
}
fn.bind1({a:1}, 1,23,4)
console