js高级继承

原型链继承

方式一:原型链

  1. 套路

    1. 定义父类型和构造函数
    2. 给父类型的原型添加方法
    3. 定义子类型的构造函数
    4. 创建父类型的对象赋值给子类型的原型
    5. 将子类型原型的构造属性设置为子类型
    6. 给子类型原型添加方法
    7. 创建子类型的对象:可以调用父类型的方法
  2. 关键

    1. 子类型的原型为父类型的一个实例对象
    //定义父类型和构造函数
            function Supper(){
                this.supProp='father'
            }
    
            //给父类型的原型添加方法
            Supper.prototype.showFather=function(){
                console.log(this.supProp);
            }
    
            //定义子类型的构造函数
            function Childen(){
                this.chiProp='childen'
            }
    
            //子类型的原型为父类型的一个实例对象
            Childen.prototype=new Supper()
    
            //让子类型原型的constructor指向子类型
            Childen.prototype.constructor=Childen
            //给子类型原型添加方法
            Childen.prototype.showChilden=function(){
                console.log(this.chiProp);
            }
    
            var childen1=new Childen()
            childen1.showFather()
            console.log(childen1.constructor);
    

方式二:借用构造函数继承(假的:这是调用不是继承)

  1. 套路

    1. 定义父类型构造函数
    2. 定义子类型构造函数
    3. 在子类型构造函数中调用夫类型构造函数
  2. 关键

    1. 在子类型构造函数中通过call()调用父类型构造函数
    function Person(name,age){
                this.name=name
                this.age=age
            }
            function Student(name,age,price){
                Person.call(this,name,age)
                this.price=price
            }
    
            var s=new Student('Tom',20,14000)
            console.log(s.name,s.age,s.price);
    

方式三:原型链+借用构造函数的组合继承

  1. 利用原型链实现对父类对象方法的继承

  2. 利用call()借用夫类型否早函数初始化相同属性

    function Person(name,age){
                this.name=name
                this.age=age
            }
    
            Person.prototype.setName=function(name){
                this.name=name
            }
    
            function Student(name,age,price){
                Person.call(this,name,age)//为了得到属性
                this.price=price
            }
    
            Student.prototype=new Person()//为了得到父类型的方法
            Student.prototype.constructor=Student//修正constructor属性
            Student.prototype.setPrice=function(price){
                this.price=price
            }
    
            var s=new Student('Tom',20,14000)
            s.setName('Bob')
    
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值