上一节原型链可以实现简单的继承,那原型链继承存在什么问题,以及哪种方式能够完美的实现继承
- 原型链继承:将父类的实例作为子类的原型
// 由于所有Child实例原型都指向同一个Parent实例, 因此对某个Child实例的父类引用类型变量修改会影响所有的Child实例
// 在创建子类实例时无法向父类构造传参, 即没有实现super()的功能
Grand.prototype.lastName = "cc"
function Grand() { }
let grand = new Grand()
Father.prototype = grand
function Father() {
this.name = "hh"
}
let father = new Father()
Son.prototype = father
function Son() {}
let son = new Son()
//想继承grand的lastName 但是father的name也会继承
//son.name = "hh"
//son.lastName = "cc"
特点:过多继承没用的属性;无法实现多继承;无法向父类构造函数传参
2. 借用构造函数:使用父类的构造函数来增强子类实例
//不能继承借用构造函数的原型;每次构造函数都要多走一个函数,运行时没有省,
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, grade) {
Person.call(this, name, age, sex)
this.grade = grade;
}
var student = new Student('cc', 18, '女', 100)
特点:可以实现多继承;只能继承父类的实例属性和方法,不能继承原型属性和方法;无法实现函数服用
3. 共享原型:公用同一个原型对象
// 不能有自己独立的属性
Father.prototype.name = '车车'
function Father() {}
function Son() {}
Son.prototype = Father.prototype
let father = new Father()
let son = new Son()
Son.prototype.sex = '女' //father也会有sex
console.log(father.sex)
特点:不能随便改动自己的原型不能拥有自己独特属性,因为改变自己会影响他人
4. 圣杯模式:就是添加一个中间层
Father.prototype.name = '车车'
function Father() {}
function Son() {}
function Fn() {}
Fn.prototype = Father.prototype;
Son.prototype = new Fn()
// 进行归位
Son.prototype.constructor = Son
let father = new Father()
let son = new Son()
Son.prototype.sex = '女'
console.log(son.name)
console.log(father.sex) //undefined
console.log(Son.prototype.constructor) //Father 指向紊乱 应该指向Son 所以上面进行归位
5.ES6中的继承
class Father {
constructor(name) {
this.name = name
}
my() {
console.log(this.name)
}
}
class Son extends Father {
constructor(name, age) {
super(name)
// super 类似于 Father().call(this,name)
this.age = age
}
}
var father = new Father('bb')
var son = new Son('cc', 18)
console.log(son) //Son { name: 'cc', age: 18 }
console.log(father) //Father { name: 'bb' }