TIL #5 //ES6 Class, Super

이윤주·2020년 1월 3일
0

Class

원래 JavaScript에서는 class를 사용하지 않았지만 "ECMAScript 2015"에서 공식적으로 ES6를 소개하면서 제공되었다. 기존에는 prototype 속성을 이용해 객체지향언어를 구현했으나 Class 함수를 사용함으로써 객체를 생성하고 상속을 다루는데 있어 훨씬 더 단순하고 명확한 문법을 제공한다.

Class 선언

class를 선언은 클래스 키위드와 클래스로 지정할 이름을 선언한 후 structure영역과 메서드영역을 객체의 스코프 영역에 담는다. 객체안의 메서드부분들은 따로 쉼표가 필요하지 않다.

class Person {
  constructor() { // constructor 선언
    this.food = "chicken"; // this로 속성 지정
    this.color = "grey";
  }

  favFood() { // method 영역
    return `Favorite food is ${this.food}.`
  }
}
const man = new Person(); // instance 생성
man.favFood(); // "favorite food is chicken"

Class 표현식

class 표현식은 클래스 다음에 이름(식별자)을 요구하지 않을 수 있다. 그 외에는 클래스 선언과 동일하다

// unnamed
let Person = class { 
  constructor(food, color) { // constructor 선언
    this.food = food; // this로 속성 지정
    this.color = color;
  }
  favFood() { // method 영역 
    return `Favorite food is ${this.food}`
  }
}
const man = new person("soup", "black"); // instance 생성
man.favFood(); // "favorite food is soup"

만약 이름을 부여하고 싶다면 클래스 키워드 다음에 이름을 주입한다.

// named
let Person2 = class Preson3 {
  constructor() { // constructor 선언
    this.food = food; // this로 속성 지정
    this.color = color;
  }
  favFood() { // method 영역 
    return `Favorite food is ${this.food}`
  }
}
const man = new Person2(); // instance 생성
man.favFood(); // "favorite food is soup"

extends를 통한 클래스 상속

extends 키워드는 클래스 선언이나 클래스 표현식에서 다른 클래스의 자식 클래스를 생성하기 위해 사용된다.

class Person { 
  constructor() {
    this.food = food; 
    this.color = color;
  }
  favFood() { 
    return `Favorite food is ${this.food}`
  }
}
// Person 클래스를 상속받는 man 클래스 생성
class man extends Person { 
  
}

extend 키워드를 사용하였을때 man 클래스는 __ proto __가 Person을 가르키고 있으므로 상속된 것을 확인할 수 있다.

Screenshot from 2020-01-05 13-21-33.png

super

super 키워드는 객체의 부모가 가지고 있는 함수들을 호출하기 위해 사용된다.

class Person { 
  constructor() {
    this.food = "soup"; 
    this.color = "yellow";
  }
  favFood() { 
    return `Favorite food is ${this.food}`
  }
}

// Person 클래스를 상속받는 man 클래스 생성
class man extends Person { 
  constructor() {
    super(); // Person의 모든 속성을 호출 this 접근전에 호출해야 한다.
    this.color = 'blue'; // 속성값 재 할당 가능 
    this.drink = "Beer" // 새로운 속성값도 정의 가능
  }
    favColor() {
      return `Favorite color is ${this.color}`
    }
    favDrink() { // 새로운 메서드 작성
      return `Favorite drink is ${this.drink}`
    } 
    favFood() { // Person의 메서드 가져오기
      return super.favFood()
	}
}

var Man = new man() 
console.log(Man.favColor()) // "Favorite color is blue"
console.log(Man.favDrink()) // "Favorite Drink is Beer"
console.log(Man.favFood()) // "Favorite food is chicken"

super 키워드는 extend 키워드를 이용한 파생 클래스에서만 사용 가능하며 super()는 this를 초기화할 책임이 있기 때문에 super()를 호출하기 전에 this에 접근하려고 하면 에러가 발생한다. 따라서 생성자에서 this에 접근하기 전에 super()를 호출해야다.

0개의 댓글