[SEB_FE] 객체 지향 프로그래밍 / 프로토타입 체인 / 상속

seunghyo·2023년 3월 16일
0

SEB_FE

목록 보기
19/38
post-thumbnail

💡 상속


상속을 javascript에서 구현할 때 프로토타입 체인을 사용한다.

//mdn
function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};
//메소드 정의
Person.prototype.greeting = function() {
  alert('Hi! I\'m ' + this.name.first + '.');
};
//선생 클래스
function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

Teacher() 생성자의 call() 함수는 부모클래스인 Person()을 Teacher()가 상속받게한다. call()함수의 첫번째 매개변수는 다른 곳에서 정의한 함수를 현재 컨텍스트에서 실행할수 있도록 한다. 나머지는 실제 함수 실행에 필요한 인자들을 전달하면 된다. 매개변수가 없는 생성자를 상속할때는 call()의 매개변수에도 아무것도 전달할 필요가 없다.

💡 프로토타입과 생성자 참조 설정

Person()의 prototype 속성을 참조 받기 위해서는

Teacher.prototype = Object.create(Person.prototype);

create(), 새 객체를 생성하여 Teacher.prototype으로 할당했다.
새 객체는 Person.prototype 객체를 자신의 프로토타입으로 가지고 있으므로 Person.prototype에 정의된 모든 메소드를 사용할 수 있다.

//새 Teaceher() 인스턴스 생성하기
var teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');

💡 ECMAScript 2015 클래스


class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first,
      last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first}`);
  };

  farewell() {
    console.log(`${this.name.first} has left the building. Bye for now!`);
  };
}
  • constructor() 메소드는 Person 클래스의 생성자를 의미.
  • greeting() and farewell()는 멤버 메소드.
  • 클래스의 메소드는 생성자 다음에 아무 메소드나 추가할 수 있다

0개의 댓글