js继承、深度复制
2020-03-31 本文已影响0人
redpeanuts
继承
//父类
function parent(name) {
this.name = name
}
//父类原型
parent.prototype.getName = function() {
return this.name
}
/*此处不能用箭头函数,因为词法作用域将this指向全局对象window,如果不用this则可以
parent.prototype.getName = () => {
return this.name
}
*/
//其他父类
function other(addr) {
this.addr = addr
}
other.prototype.getAddr = function() {
return this.addr
}
//子类
function child(age, name, addr) {
other.call(this, addr)
parent.call(this, name)
this.age = age
}
child.prototype.getAge = function() {
return this.age
}
//若子类原型添加属性则这一步是必须的,否则会访问不到
let cprototype = child.prototype
child.prototype = Object.create(parent.prototype)//单继承推荐这样写,修改child中的属性不会影响parent的prototype
Object.assign(child.prototype, cprototype, other.prototype) //混合other的prototype
child.prototype.constructor = child //将构造函数指向child
let c = new child(22, 'tom', 'us')
console.log(c.getAge()) //22
console.log(c.getName())//tom
console.log(c.getAddr())//us
复制
function dp(obj) {
if (typeof obj !== 'object') return // 如果属性为空则递归结束
let newobj = obj instanceof Array ? [] : {}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newobj[key] = typeof obj[key] === 'object' ? dp(obj[key]) : obj[key]
}
}
return newobj
}