js继承

作者: Birdd | 来源:发表于2022-06-17 16:35 被阅读0次

    1.es6得继承

    class Person{
        constructor(){
            this.age = 20
        }
    }
    
    class Boy extends Person{
        constructor(){
        super();
            this.name = '张三'
        }
    }
    
    let boy = new Boy()
    conslo.log(boy)
    

    2.原型链继承

    function Car(){
        this.lunzi = 4
    }
    
    function Audi(){
        this.name = '奥迪'
    }
    
    Audi.prototypr = new Car()
    let audi = new Audi()
    console.log(audi)
    

    3.借用构造函数继承

    function Car(){
        this.lunzi = 4
    }
    
    function Audi(){
        Car.call(this)
        this.name = '奥迪'
    }
    let audi = new Audi()
    console.log(audi)
    

    4.组合继承

    function Car(){
        this.lunzi = 4
    }
    
    function Audi(){
        Car.call(this)
        this.name = '奥迪'
    }
    
    Audi.prototypr = new Car()
    let audi = new Audi()
    console.log(audi)
    

    5.拷贝继承

    function Cat(name){
      var animal = new Animal();
      for(var p in animal){
        Cat.prototype[p] = animal[p];
      }
      this.name = name || 'Tom';
    }
    
    // Test Code
    var cat = new Cat();
    

    6.寄生组合继承

    function Cat(name){
      Animal.call(this);
      this.name = name || 'Tom';
    }
    (function(){
      // 创建一个没有实例方法的类
      var Super = function(){};
      Super.prototype = Animal.prototype;
      //将实例作为子类的原型
      Cat.prototype = new Super();
    })();
    
    // Test Code
    var cat = new Cat();
    

    相关文章

      网友评论

          本文标题:js继承

          本文链接:https://www.haomeiwen.com/subject/gilhvrtx.html