JS高级——继承

面向对象编程——继承性

        将对象得属性和方法进行传递 原型链,改变this得指向性问题

        三种继承方式,将以实例演示:

“创建一个人类然后继承学生类以及教师类”

function Human(name,age){
    this.name=name
    this.age=age
}
Human.prototype.move=function(){
    console.log(this.name+'在走路')
}
Human.prototype.rest=function(){
    console.log(this.name+'正在休息')
}

原型继承:

        原型链

缺点:所有的属性值都和Human对象一样

Student.prototype=new Human("继承",21)
Student.prototype.study=function(){
      console.log(this.name+"正在学习")
}
var t1=new Student("张三",18)
console.log(t1)
console.log(t1.name)
t1.study()
var t2=new Student("李四",21)
console.log(t2)


冒充继承:

        通过改变this的指向性,实现的继承方法

缺点:无法继承原型,只是调用了一次函数

    function Teacher(name, age) {
      //在构造函数中,将Human的属性都挂载过来
      //改变this的指向性
      Human.call(this, name, age) //this指向  window
    }
    Teacher.prototype.class = function () {
      console.log(this.name + "讲课")
    }
    var d1 = new Teacher("诸葛亮", 38)
    console.log(d1) //没有属性、Human中的this并没有指向 new创建的对象
    d1.class()
    d1.rest()//调用原型失败

注:

this对象指向:指向对象

        函数调用:this指向三种  

        1.由new调用,指向构造函数创建出来的对象

        2.在window下调用,window对象

        3.对象中调用或者事件过程中调用, 指向调用的对象


组合继承:

    function parent(name, age, a) {
      this.a = a        //将Human的属性都挂载过来
      Human.call(this, name, age)        //让Human中的this和parent中this相同
    }
    parent.prototype = new Human()
    parent.prototype.work = function () {
      console.log(this.name + "在工作")
    }
    var c1 = new parent("father", 40)
    console.log(c1)
    c1.work()
    c1.rest()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值