TIL 18 | JavaScript Class, Inheritance, Super

ym j·2021년 3월 23일
0

사전스터디 

목록 보기
18/23
post-thumbnail

Class란??

  • class는 일종의 객체를 찍어내는 틀이다.

  • ES6(2015)에 추가된 함수 문법이다. (typeof를 통해 함수임을 알 수 있으며 객체가 아님을 유의하자!)

  • 생성자 함수new 키워드를 통해 유사한 형태의 객체를 여러개 생성했던 것처럼, class문법을 사용하여 객체 및 해당 객체에 소속된 메소드를 생성할 수 있다. 이때 생성된 객체를 인스턴스라고 한다.



How to use it?

class Person { 					// class 선언
  constructor(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  speak() { 					//method 선언
    console.log(`${this.name}: hello`);
  }
}
//
const yongmin = new Person('yongmin', 28, 'male'); // 클래스 호출, 인스턴스 생성, 변수 할당
//
console.log(yongmin) 		// Person {name: "yongmin", age: 29, gender: "male"}
console.log(yongmin.name); 	// yongmin
console.log(yongmin.age); 	// 29
console.log(yongmin.gender); 	// male
yongmin.speak(); 		// yongmin: hello
  • 위 예제처럼, Person이라는 class를 선언한 후 호출 및 변수에 할당함으로써 인스턴스를 생성할 수 있다.

  • 호출시 constructor의 매개변수 개수만큼의 인자가 필요하다. (물론 없을시 default parameter를 설정해주기도 하지만, 이는 나중에 생각해야겠다.)

  • 생성된 인스턴스의 내부 메소드를 통해 yongmin: hello 를 출력할 수 있으며 이때의 this 값은 속한 인스턴스를 가리킨다.


Inheritance (상속)

class Person { 					// 부모 class 선언
  constructor(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  speak() { 					// method 선언
    console.log(`${this.name}: hello`);
  }
}
//
class PersonPlus extends Person{ //부모 class로부터 상속받는 새로운 자식 class 선언
  ageMultiple() {
	return this.age*2 // PersonPlus만의 메소드 생성 
  }
}  
const cheolsu = new Person('cheolsu', 24, 'male');
const yongmin = new PersonPlus('yongmin', 28, 'male');
//
console.log(yongmin) // PersonPlus {name: "yongmin", age: 29, gender: "male"}
console.log(yongmin.speak()) // yongmin: hello
//
console.log(cheolsu.ageMultiple()) // Uncaught TypeError
console.log(yongmin.ageMultiple()) // 56
  • 상속이란, 기존의 클래스를 재사용 및 새로운 클래스에 적용하고자 할때 사용한다.

  • 새로운 클래스를 다시 선언하여 코드를 작성할 수 있지만, 상속을 통해 중복의 제거 및 재사용성을 높일 수 있다.

  • 상속 받는 클래스를 자식클래스, 상속을 하는 클래스를 부모클래스라 한다.

  • class 자식클래스 extends 부모클래스 의 형태로 작성한다.

  • 위 예제처럼 Person의 상속을 받는 PersonPlus를 통해 yongmin이라는 인스턴스를 생성할 수 있었다.

  • 상속받는 자식 class에서 메소드를 새로 선언할 경우, 이는 자식 class 고유의 메소드가 된다. (위 예제에서 Person class를 통해 생성된 cheolsu라는 인스턴스가 PersonPlus class에 선언된 ageMultiple메소드에 접근하지 못하는 것을 통해 알 수 있다.)


1. super( )

class Person { 					// 부모 클래스
  constructor(name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
  }
//
  add() {
    const result = this.first + this.second;
    return result;
  }
}
class PersonPlus extends Person {		// 자식 클래스(super()사용 X)
  constructor(name, first, second, third) {
    this.name = name;			// super을 사용하지 않을 시 this에 접근 불가(오류)
    this.first = first;					
    this.second = second;
    this.third = third;
  }
//
  add() {
    const result = this.first + this.second + this.third;
    return result;
  }
}
 const person1 = new PersonPlus('영희', 100, 200, 300); /*Uncaught ReferenceError: 
 					Must call super constructor in derived 
 		class before accessing 'this' or returning from derived constructor */
class PersonPlus extends Person { 		// 자식 클래스 (super()사용)
  constructor(name, first, second, third) {
    super(name, first, second);			// super을 통해 부모 constructor 호출
    this.third = third;				// 기존 constructor에 third 변수 추가
  }
  add() {
    const result = super.add() + this.third;	// method 또한 변경 가능
    return result;
  }
}
//
const person1 = new PersonPlus('영희', 100, 200, 300);
//
console.log(person1.add()) 			//600
  • super 키워드는 부모 클래스를 참조할 때 또는 부모 클래스의 constructor를 호출할 때 사용한다.

  • super을 통해 constructor에 매개변수를 추가하여 변경할 수 있으며, 메소드 또한 변경할 수 있다.

  • 상속을 받는 자식 클래스에서 super 키워드를 사용하지 않을 시, 인스턴스를 가리키는 this에 접근할 수 없으며 참조 오류가 발생한다.



Reference

profile
블로그를 이전하였습니다 => "https://jymini.tistory.com"

2개의 댓글

comment-user-thumbnail
2021년 3월 23일

constructer만 알고 있었는데 저도 얼른 class 공부해야겠어욧!!!!✏️✏️

1개의 답글