组合继承 :将原型链通过构造函数的方法将技术组合在一起。
此继承方式的核心是在子类的构造函数中通过parent.call(this)继承父类的属性,然后改变子类的原型为new parent()来继承父类的函数。
this.val = value
}
// 给parent的原型上写了一个getValue方法
Parent.prototype.getValue = function () {
console.log(this.val)
}
// 在child函数内部调用parent并且将parent的this指向改为child的指向
function Child(value) {
Parent.call(this, value)
}
// 将parent方法写到child的原型上
Child.prototype = new Parent()
const child = new Child(1)
child.getValue() // 1
寄生式继承
这种继承方式对组合继承进行了优化,组合继承缺点在于继承父类函数时调用了构造函数,我们只需要优化掉这点就行了。
以上继承实现的核心就是将父类的原型赋值给了子类,并且将构造函数设置为子类,这样既解决了无用的父类属性问题,还能正确的找到子类的构造函数。子类的proto指向的是父类,父类的构造函数为子类,父类的属性就是子类的属性,
configurable:false,//能否使用delete、能否需改属性特性、或能否修改访问器属性、,false为不可重新定义,默认值为true
enumerable:false,//对象属性是否可通过for-in循环,flase为不可循环,默认值为true
writable:false,//对象属性是否可修改,flase为不可修改,默认值为true
value:'xiaoming' //对象属性的默认值,默认值为undefined
// 构造一个函数
function Parent(value) {
this.val = value
}
//在parent函数的原型上定义一个getValue的方法
Parent.prototype.getValue = function() {
console.log(this.val)
}
//构造child函数在函数内调用parent函数写在原型上的方法
function Child(value) {
Parent.call(this, value)
}
//
Child.prototype = Object.create(Parent.prototype, {
//此处的constructor是指回去的意思
constructor: {
value: Child,
enumerable: false,
writable: true,
configurable: true
}
})
const child = new Child(1)
child.getValue() // 1
child instanceof Parent // true
CLASS继承
class Parent {
constructor(value) {
this.val = value
}
getValue() {
console.log(this.val)
}
}
class Child extends Parent {
constructor(value) {
super(value)
this.val = value
}
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true