TIL (today I learned)
TIL_2019-09-23 [ES6 class 와 extends, super 키워드]
grin-quokka
2019. 9. 23. 15:42
ES6 class 와 extends, super 키워드
-
MDN (https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/class)
-
ES6에서 클래스를 정의할 때는 class 키워드를 사용한다. 보통 클래스 이름의 첫글자를 대문자로 쓴다.
- constructor는 옵션이다.
1 2 3 4 5 6 7 8 9 | class Phone { constructor(brand){ this.brand = brand; } sendMsg(msg){ console.log(msg); } } | cs |
-
객체의 인스턴스를 생성할 때는 new 키워드를 사용한다.
1 2 3 | var iphone = new Phone("apple"); console.log(iphone.brand); // apple iphone.sendMsg('Hi!'); // Hi! | cs |
-
-
다른 클래스를 상속 받기 위해서 사용
-
오버라이딩은 할 수 있지만, 오버로딩은 안된다.
-
1 2 3 | class Parent {} class Child extends Parent {} | cs |
-
-
다른 클래스를 상속 받으려는 자식 클래스의 생성자 함수 내에서 사용된다.
-
부모 객체의 생성자 함수(constructor)를 호출하거나 부모의 다른 메소드를 호출할 때 쓴다.
- 부모 객체의 생성자 함수를 호출 할 때 super(brand, color)
- 부모 객체의 다른 메소드를 호출 할 때 super.sendMsg(msg)
-
super()는 생성자 내에서만 쓸 수 있고, this 키워드를 사용하기 전에만 쓸 수 있다. super() 함수를 호출하기 전에는 this 키워드를 쓸 수 없다.
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Phone { constructor(brand){ this.color = "black"; this.brand = brand; } sendMsg(msg){ console.log(msg); } } class Iphone extends Phone { constructor(brand){ super(brand); this.color = "gray"; } } var myphone = new Iphone("apple"); myphone.sendMsg("hello"); // hello console.log(myphone.color); // gray | cs |