类和类的继承

1.类的声明

//es6之前
function A(){
    this.name='A'
}

//es6之后
class A{
    constructor(){
        this.name='A'
    }
}

2.类的继承

1)通过改变this指向
function People(name,age){
    this.name=name
    this.age=age
}
People.prototype.toInfo = function(){
    console.log('name:'+this.name)
    console.log('age:'+this.age)
    console.log('sex:'+this.sex)
}
function Man(name,age){
    this.sex='man'
    People.call(this,name,age)
}
function Woman(name,age){
    this.sex='woman'
    People.call(this,name,age)
}
let man = new Man('张三',20)
let woman = new Woman('李四',18)
console.log(man)
console.log(woman)
image.png

我们可以看到name和age属性实现了继承

man.toInfo()
image.png

当我们调用 toInfo方法的时候提示toInfo不是方法,因我们toInfo我们定义在了People.prototype上,通过改变this指向是没有办法继承prototype属性的

2)原型链继承
function People(){
    this.been = ['北京','上海','广州']
}
People.prototype.toInfo = function(){
    console.log('name:'+this.name)
    console.log('age:'+this.age)
    console.log('sex:'+this.sex)
    console.log('been:'+this.been)
}
function Man(name,age){
    this.sex='man'
    this.name = name
    this.age = age
}
Man.prototype = new People()
    
function Woman(name,age){
    this.sex='woman'
    this.name = name
    this.age = age
}
Woman.prototype = new People()

let man = new Man('张三',20)
let woman = new Woman('李四',18)
man.toInfo()
woman.toInfo()
image.png

我们实现了继承并能调用到对应方法,但这个时候新来了一个Man他除了去过 ['北京','上海','广州'] 还去过 深圳

let man2 = new Man('王五',22)
man2.been.push('深圳')

man.toInfo()
man2.toInfo()
image.png

我们发现给王五添加去过深圳,张三也去过了,
原型继承的弊端:修改原型属性,所有继承自这个原型的对应属性也会修改

2)组合继承
function People(name,age){
    this.name = name
    this.age = age
    this.been = ['北京','上海','广州']
}
People.prototype.toInfo = function(){
    console.log('name:'+this.name)
    console.log('age:'+this.age)
    console.log('sex:'+this.sex)
    console.log('been:'+this.been)
}
function Man(name,age){
    this.sex='man'
    People.call(this,name,age)
}
Man.prototype = new People()
    
function Woman(name,age){
    this.sex='woman'
    People.call(this,name,age)
}
Woman.prototype = new People()

let man = new Man('张三',20)
let woman = new Woman('李四',18)
let man2 = new Man('王五',22)
man2.been.push('深圳')

man.toInfo()
woman.toInfo()
man2.toInfo()

组合继承既能有效继承各个属性,又能隔离原型属性,防止修改属性相互影响

组合继承优化

console.log(man.constructor)
image.png

我们可以看到man.constructor指向People而实际应该指向Man

function People(name,age){
    this.name = name
    this.age = age
    this.been = ['北京','上海','广州']
}
People.prototype.toInfo = function(){
    console.log('name:'+this.name)
    console.log('age:'+this.age)
    console.log('sex:'+this.sex)
    console.log('been:'+this.been)
}
function Man(name,age){
    this.sex='man'
    People.call(this,name,age)
}
//继承People.prototype
Man.prototype = Object.create(People.prototype)
//重新指定constructor
Man.prototype.constructor = Man
    

let man = new Man('张三',20)
console.log(man.constructor)
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。