const father = {
age: 56,
name: ['老邓头', '臭屁爹', '老顽童'],
eat: function() {
console.log('==00老邓头我喜欢喝点小酒', this.age)
},
children: {
age: 28,
name: ['小邓子', '小顽童'],
eat: function() {
console.log('小邓我喜欢喝汤')
},
grandson: {
age: 2,
name: ['全局团宠'],
eat: function() {
console.log('座为团宠我喜欢喝粥')
}
}
}
}
// 基本数据类型直接拷贝,引用数据类型直接赋值只是引用了原数据的路径
const obj1 = JSON.parse(JSON.stringify(father))
// JSON深度复制,如果有属性是function,该属性不被复制,其他属性正常深度复制===》可用于没有使用fn的对象进行深度拷贝
const obj2 = Object.assign(father)// 没使用{}合并成新对象,这样合并father===obj2
const obj3 = Object.assign({}, father)// 这样复制到一个空{},可以实现第一层深度复制
// Object.assign只能深度拷贝对象上第一层属性,对象里面的对象是浅拷贝===》可用于只有一层对象的拷贝
// 可用递归方式实现深度赋值:Object.prototype.toString.call(arr)
// for in =》对于对象来说,prop是key;对于数组,prop是索引
function deepClone(origin, target) {
target = target || {}
const toStr = Object.prototype.toString
for (const prop in origin) {
if (origin.hasOwnProperty(prop)) { // ===> hasOwnProperty是为了判断属性直接是在对象上,而不是在原型上, 因为说不定这个对象有原型
if (typeof origin[prop] === 'object' && origin[prop] !== null) {
if (toStr.call(origin[prop]) === '[object Object]') {
target[prop] = {}
} else {
target[prop] = []
}
deepClone(origin[prop], target[prop])
} else {
target[prop] = origin[prop]// ==>赋值
}
}
}
return target
}
/* 《检测数据类型》
1、typeof:可以判断基本数据类型(只能判断基本类型,fn特殊判断是fn,null判断是obj)
2、instanceof :运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上:
object instanceof constructor ====》[] instanceof Array === true =>true / [] instanceof Array === Object =>false
3、constructor是通过与构造函数对比判断数据类型(除了null和undefined,其他属性类型都能判断)
》undefined 和 null 没有 constructor 属性,所有不能用其判断
》object.constructor === 构造函数 ===》eg:father.constructor===Array =>true / father.constructor===Object =>false
4、toString():是 Object 的原型方法,它能够返回当前对象的字符串表示;
可以通过 toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为 thisArg。
*(固定)instanceof不能判断基本数据类型;typeof不能判断引用数据类型;
(所有数据类型)constructor都能判断;toString能检测所有数据类型
hasOwnProperty:
》》注意:const object1 = new Object();object1.property1 = 42;console.log(object1.hasOwnProperty('property1'));
hasOwnProperty是为了判断属性直接是在对象上,而不是在原型上, 因为说不定这个对象有原型
《this指向》
call/apply都是改变this指向,任何方法都可以.call
function test() { console.log('11我是谁') }
test() === test.call() === test.apply()
function Father(name, age, sex) { // 行参
console.log(this, '===我是this')
// 相当于有个隐形的this={}对象,执行完return this对象出去
this.name = name,
this.age = age,
this.sex = sex
}
Father()// 这里打印出来的this指向是window
const obj = {}
Father.call(obj)// this指向obj
Father.call(obj, '我是name', '我是age', '我是sex')// 实参