原型链继承,构造继承,组合继承

什么是继承?

继承 是 面向对象 软件技术当中的一个概念,与 多态 、 封装 共为 面向对象 的三个基本特征。 继承可以使得子类具有父类的 属性 和 方法 或者重新定义、追加属性和方法等。

原型链继承

实现:Child.prototype = new Father()
特点:将父类的私有和原型属性全部座位子类的原型属性

原型继承 只继承原型属性
首先定义一个函数(作为父类)

    function Father(name) {
       this.name = '张'
    }
    //添加原型属性
    Father.prototype.location = '天津'
    const f1 = new Father()
    console.log(f1)
复制代码

定义子类(继承父类)

    function Child(school) {
      this.school = school
      this.name = '刘'
    }
复制代码

使用原型链继承

Child.prototype = new Father()

    //实例化子类
    const s1 = new Child('清华')
    console.log(s1)
复制代码

这样就完成了原型链继承

构造继承

特点:只承私有属性

定义父类

function Father (name,age){
  this.name=name
  his.age=age 
}
复制代码

定义子类

function Child(name,age,school){
   Father.call(this,name,age)
   this.school=school
}
   // 实例化
const s1 = new Child('张三',23,'清华')
console.log(s1)
复制代码

组合继承:原型链继承+构造继承

原型链继承:将父类的私有属性和原型属性,全部作为子类的原型属性
构造属性:将父类的私有属性,作为子类的私有属性

function Father(name, age) {
        this.name = name
        this.age = age
    }

    Father.prototype.say = function () {
        console.log('hello world')
    }

    function Child(name, age, school) {
        //构造继承
        Father.call(this, name, age)
        this.school = school
    }

    // 原型继承
    Child.prototype = new Father()
    //修组 constructor 指向
    Child.prototype.constructor = Child
    // 实例化子元素
    const c1 = new Child('张三', 23, '清华')
    console.log(c1)
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享