js中常见的继承

js中常见的继承

  1. 原型链继承
    // 1.原型链继承
    /*
        缺点:所有属性被共享,而且不能传递参数
    */
    function Person(name,age){
        this.name = name
        this.age = age
    }
    Person.prototype.sayName = () =>{
        console.log(this.name)
    }
    function Man(name){
    
    }
    Man.prototype = new Person()
    Man.prototype.name = 'zhangsan'
    var zhangsan = new Man('zhangsan')
    console.log(zhangsan.name) //zhangsan
    
  2. 构造函数继承(call)
    // 构造函数继承(经典继承)
    /* 
        优点:可以传递参数
        缺点:所有方法都在构造函数内,每次创建对象都会创建对应的方法,大大浪费内存
    */
    function Perent(name,age,sex){
        this.name = name
        this.age = age
        this.sex = sex
        this.sayName = function(){
            console.log(this.name)
        }
    }
    
    function Child(name,age,sex){
        Perent.call(this,name,age,sex)
    }
    let child = new Child('lisi' , 18, '男')
    console.log(child)   //Child { name: 'lisi', age: 18, sex: '男', sayName: [Function] }
    
  3. 组合方式继承(构造函数(call) + 原型链)
    // 3.组合模式(构造函数 + 原型链)
    /* 
        这种方式充分利用了原型链与构造函数各自的优点,是JS中最常用的继承方法
    */
    function Animal(name,age){
        this.name = name
        this.age = age
    }
    Animal.prototype.sayName = function () {
        console.log(this.name)
    }
    function Cat(name,age,color){
        Animal.call(this,name,age)
        this.color = color
    }
    Cat.prototype = Animal.prototype  //将Cat的原型指向Animal的原型
    Cat.prototype.constructor = Cat   //将Cat的构造函数指向Cat
    let cat = new Cat('xiaobai',3,'white')
    console.log(cat) //Cat { name: 'xiaobai', age: 3, color: 'white' }
    cat.sayName()   //xiaobai
    
  4. es6中的extends继承
    class Animal{
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        
        getName() {
            return this.name
        }
    }
    
    // Dog类继承Animal类
    class Dog extends Animal{
        constructor(name, age, sexual, color) {
            super(name, age);
            this.sexual= sexual; //父类没有,如果需要则在子类这里定义自己的特例
            this.color= color;
        }
        
        getColor() {
            return this.color;
        }
    }
    let dog = new Dog('zhangsan',18,11,'red')
    console.log(dog) //{name: "zhangsan", age: 18, sexual: 11, color: red}
    console.log(dog.getName()) //zhangsan
    console.log(dog.getColor()) //**red**
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

teng28

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值