美文网首页
JS类的继承

JS类的继承

作者: 麻辣小面瘫 | 来源:发表于2018-01-14 21:49 被阅读0次

    1.类式继承

      function Person(name,age){
        this.name = name;
        this.age = age ;
        this.instances = ['1','2','3']
      }
      Person.prototype.getName = function(){}
    
      function Man(){}
      Man.prototype = new Person('jack',25);  //继承父类
      Man.prototype.getAge = function(){};
      
      var man = new Man();
      console.log(man instanceof Man); //true
      console.log(man instanceof Person); //true
      console.log(Man  instanceof Person); //false 这里并不是实例关系;是Man.prototype继承了Person
      console.log(Man.prototype instanceof Person); //true
      问题: 如果父类中的公共属性是引用类型,则会被所以实例共享,且被修改后同时做出变动;
      var man1 = new Man();
      console.log(man.instances );  // ['1','2','3']
      console.log(man1 .instances );   // ['1','2','3']
      man1.instances.push('4');
      console.log(man.instances );   // ['1','2','3','4']
    
    1. 构造函数继承
      function Person(age){
        this.age = age ;
        this.instances = ['1','2','3']
      }
      Person.prototype.getName = function(){}
    
      function Man(sexy){
        Person.call(this,'13'); //使用call来完成
        this.sexy = sexy;
      }
      var man1 = new Man('s1');
      var man2 = new Man('s2');
      man1 .instances.push('4');
      console.log(man2.instances) ; //  ['1','2','3'];
      //不同的对象都进行了实例化
      man1 .getName() //TypeError 因为没有继承原型链
      
    

    3.组合继承

       function Person(age){
        this.age = age ;
        this.instances = ['1','2','3']
      }
      Person.prototype.getName = function(){}
    
      function Man(sexy){
        Person.call(this,'13');
        this.sexy = sexy;
      }
      Man.prototype = new Person();
      注:组合继承是 类式继承与构造函数继承的结合;
      问题:调用了两边父类函数:call/new Person()
    

    4.原型继承

      function inheritObject(o){
        function F(){};
        F.prototype = o;
        return new F(); //返回过度对象的一个实例,
      }
      var person = {
        name : 'jack',
        instances : ['1','2','3']
      }
      var p1 = inheritObject(person );
      p1.name = '111'; //111
      p1.instances.push('4'); // ["1", "2", "3", "4", "5"]
      var p2 = inheritObject(person );
      p2.name = '222';  //222
      p2.instances.push('5'); // ["1", "2", "3", "4", "5"]
      注: 与类式继承一样,引用类型的值被共享了
    

    5.寄生式继承

      function inheritObject(o){
        function F(){};
        F.prototype = o;
        return new F(); //返回过度对象的一个实例,
      }
      var person = {
        name : 'jack',
        instances : ['1','2','3']
      }
      function createPerson(obj){
        var o = new inheritObject(obj);
        o.getName = function(){};
        return o;
      }
    

    6.寄生组合式继承

      function inheritPrototype(subClass,SuperClass){
        var p = inheritObject(SuperClass.prototype);
        p.constructor = subClass;
        subClass.prototype = p;
      }
    
    

    相关文章

      网友评论

          本文标题:JS类的继承

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