简单了解js继承
某些子类获取父类资源(属性|方法)的行为
为什么需要继承?
当代码变得复杂的时候,继承结构可以更好的复用代码
混入式继承(拷贝)
let o1 = {name: 'zs', friends: ['ls', 'ww']}
let o2 = {}
直接赋值(完全共享)
o2 = o1
浅拷贝
for(let k in o1){
o2[k] = o1[k]
}
深拷贝
json
不能拷贝正则、函数、undefined
o2 = JSON.parse(JSON.stringify(o1))
自己封装拷贝方法
let deepClone = (val, wm = new WeakMap) => {
if(val == null) return val
if(typeof val !== 'object') return val
if(val instanceof Date) return new Date(val)
if(val instanceof RegExp) return new RegExp(val)
if(wm.has(val)) return wm.get(val)
let _instance = new val.constructor
wm.set(val, _instance)
for(let key in val){
if(val.hasOwnProperty(key)) _instance[key] = deepClone(val[key], vm)
}
return _instance
}
原型式继承
举例
//父构造函数
let Person = function(name,age){
this.name = name
this.age = age
}
Person.prototype = {
constructor: person,
showName(){},
showAge(){},
xx:'信息'
}
//子构造函数
let Girl = function(sex = '女'){
this.sex = sex
}
Girl.prototype = Person.prototype
let g1 = new Girl()
不足:
- 只能获取父构造函数原型成员,无法获取构造函数的实例成员
- 存在共享问题,修改的时候比较麻烦
原型链继承
//父构造函数
let Person = function(name,age){...}
Person.prototype = {...}
//子构造函数
let Girl = function(sex = '女'){...}
Girl.prototype = new Person('来福', 99)
let g1 = new Girl()
不足
这种结构导致父构造实例成员成为了 子构造函数实例成员的 原型对象
无法给父构造函数传参
借用继承
//父构造函数
let Person = function(name,age){...}
Person.prototype = {...}
//子构造函数
let Girl = function(name, age, sex = '女'){
this.sex = sex
Person.call(this, name, age)
}
let g1 = new Girl('如花', 18)
不足:实例对象上没有原型成员
组合继承
原型式继承 + 借用继承
//父构造函数
let Person = function(name,age){...}
Person.prototype = {...}
//子构造函数
let Girl = function(name, age, sex = '女'){
this.sex = sex
Person.call(this, name, age)
}
Girl.prototype.__proto__ = Person.prototype
let g1 = new Girl('如花', 18)
class实现继承
可以继承父类实例成员 + 原型成员 + 静态成员
//父类
class Person {
constructor(name, age){
this.name = name
this.age = age
}
showName(){}
showAge(){}
static showPersonInfo() {
console.log("showPersonInfo")
}
}
//子类
class Girl extends Person {
constructor(name, age, sex = '女'){
super(name, age)
this.age = sex
}
}
let g1 = new Girl('zs', 22)
以上就是本人的总结,如有不对,欢迎指出~