JS 클래스의 상속

2876 단어
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']
  • 구조 함수 계승
  •   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;
      }
    
    

    좋은 웹페이지 즐겨찾기