组合继承和寄生组合继承
继承的几种方式在这里就不过多赘述查看js继承方式
这里着重记录一下组合继承和寄生继承的区别
组合继承
function Person(name) {
this.name = name,
this.age = '23'
}
Person.prototype.sayName = function(){
console.log('my name is'+this.name+'.');
}
function student(name,grade){
Person.call(this,name)
this.grade = grade
}
student.prototype = new Person()
student.prototype.constructor = student
const student1 = new student('pld','99')
console.log(student1);
一看没什么问题,父类的方法和属性都继承了过来,但是我们发现一个问题,在打印实例的时候。我们发现子类的__proto__指向的是父类实例,虽然此处不影响我们继承的目的,但是却埋下了隐患。由于原型链的存在,如我们删除子类实例的age属性,我们依然可以打印出student.age这个值。
寄生组合继承
function Person(name) {
this.name = name,
this.age = '23'
}
Person.prototype.sayName = function(){
console.log('my name is'+this.name+'.');
}
function student(name,grade){
Person.call(this,name)
this.grade = grade
}
student.prototype = Object.create(Person.prototype)
student.prototype.constructor = student
const student1 = new student('pld','99')
console.log(student1);
我们只需要做一点点更改,就是让子类的原型对象的指向父类的原型对象的实例。这样就不会在子类的原型对象上看到父类的实例属性了。