原型2

52 阅读2分钟

继承

继承是面向对象的三大特点之一,主要是子类继承父类的非私有内容

继承的实现

class的继承 extends关键词

extends继承是可以继承静态的属性和方法

原型链继承

将需要继承的父类对象放在对应的构造函数子类的原型上
function Animal(name,age){
this.name=name
this.age=age
}
// 原型上的方法
Animal.prototype.sayHello=()=>{
console.log('hello')
}
function Person(sex){
this.sex=sex
}
// 原型继承  将对应的需要被继承的父类对象放在被继承的子类的构造函数的原型上
Person.prototype.say=()=>{}//被覆盖
// Person来继承Animal   不能初始化对应的父亲的构造函数的属性  他如果写在对应的子类的原型方法赋值之后 他会覆盖对应的原型空间
Person.prototype=new Animal()
// instanceof
console.log(new Person('男') instanceof Animal)//true
console.log(new Person('男'))//Person {sex: '男'}
new Person('男').sayHello()//hello

原型链继承的缺陷

  • 不能初始化对应的父类构造中的属性
  • 他如果写在对应的子类的原型方法赋值之后 他会覆盖对应的原型空间

原型链继承的优点

它可以继承私有的父类的属性方法

对象冒充继承

// 冒充继承
function Animal(name,age){
this.name=name
this.age=age
}
Animal.prototype.sayHello=()=>{console.log('hello')}
function Person(sex,name,age){
// 调用对应的父类的构造函数  修改其this指向
Animal.call(this,name,age)
this.sex=sex
}
var person=new Person('男','jack',18)
console.log(person)
// 只能获取对应的构造函数上的内容   无法获取原型上的内容
console.log(person instanceof Animal)//false
person.sayHello()//报错
在子类中调用父类的构造函数修改其this指向

组合继承

function Animal(name,age){
this.name=name
this.age=age
}
// 原型上的方法
Animal.prototype.sayHello=()=>{
console.log('hello')
}
function Person(sex,name,age){
// 调用对应的父类的构造函数  修改其this指向
Animal.call(this,name,age)
this.sex=sex
}
// 原型链继承
Person.prototype=new Animal()
let person = new Person('女','rose',17)
console.log(person)
console.log(person instanceof Animal)
person.sayHello()

寄生组合继承

// 原型链继承
function Animal(name,age){
this.name=name
this.age=age
}
// 冒充继承
Animal.prototype.sayHello=()=>{console.log('你好')}
function Person(sex,name,age){
Animal.call(this,name,age)
this.sex=sex
}
let Animalpro=Object.create(Animal.prototype)
Animalpro.constructo=Person
Person.prototype=Animalpro
let person=new Person('男','jack',19)
console.log(person instanceof Animal)
console.log(person instanceof Person)
person.sayHello()

组合继承的缺点 原型上会有重复的属性,且对应的属性值为undefined

寄生组合继承