Inheritance Patterns

future·2021년 1월 29일
0

JavaScript

목록 보기
10/10
post-thumbnail

Pseudoclassical

  1. 생성자(constructor) 함수를 선언 후 필요한 속성을 할당해준다.
var Mufasa = function() {
  this.position = 'king';
  this.name = 'father';
  this.rakecolor = 'orange';
}
  1. prototype을 이용하여 필요한 메서드를 만들어준다.
Mufasa.prototype.hunt = function() {
  return 'hyena';
}
  1. 자식 함수를 선언 후 call 또는 apply를 통해 부모 함수의 속성들을 호출해준다.
    이때 속성의 값을 변경하고 싶을 경우 재할당해준다.
var Simba = function() {
  Mufasa.call(this);
  this.name = 'son';
  this.friends = '';
}
  1. prototype을 이용하여 부모 객체와 자식 객체를 연결해준다.
Simba.prototype = Object.create(Mufasa.prototype);
  1. 아직 생성자는 부모 함수이기 때문에 자식 함수의 constructor를 자기 자신으로 재할당해준다.
Simba.prototype.constructor = Simba;
  1. 자식 함수에 메서드를 추가하고 싶을 경우 prototype을 이용하여 추가해준다.
Simba.prototype.play = function() {
  this.friends = 'timon & pumbaa';
}

ES6 Class

  1. 부모 클래스 선언 후 생성자(constructor) 키워드를 사용하여 필요한 속성을 할당해준다.
  2. 필요한 메서드는 생성자 밖을 빠져나와 선언해준다.
class Mufasa {
  constructor() {
    this.position = 'king';
    this.name = 'father';
    this.rakecolor = 'orange';
  }
  hunt() {
    return 'hyena';
  }
}
  1. extends 키워드를 이용하여 자식 클래스 선언 후 부모 클래스의 생성자를 호출해준다.
  2. super 키워드를 사용하여 부모 클래스의 모든 속성들을 자동으로 상속시켜준다.
  3. 이때 속성값의 변경을 원할 경우 값을 재할당해준다.
class Simba extends Mufasa {
  constructor() {
    super();
    this.name = 'son';
    this.friends = '';
  }
}
  1. 자식 클래스에 메서드를 추가하고 싶을 경우 constructor 밖을 빠져나와 선언해준다.
class Simba extends Mufasa {
  constructor() {
    super();
    this.name = 'son';
    this.friends = '';
  }
  play() {
    this.friends = 'timon & pumbaa';
  }
}
profile
get, set, go!

0개의 댓글