컴/폰
Javascript ES6 class 와 모듈 (1)
양재문
2023-02-15 15:00
조회수 : 21
C++ 에서 넘어온 문법
클래스는 미리 선언해 두었다가 클래스 선언문의 이름 앞에 new 키워드를 붙여 호출하여
인스턴스를 생성하여 사용한다. 이때 클래스 안의 this 키워드는 생성된 인스턴스를 참조한다
1.선언
class 클래스명{
}
let dog = new 클래스명(); // 클래스의 첫문자는 주로 대문자로 설정하는 관습이 있다
1-1. 생성자 함수
- 클래스의 인스턴스 생성 시에 한번 호출되는 함수. 내부 구문에 의해서 호출할 수 없다
- constructor (정해진 함수명) 키워드를 사용하여 선언하고 function을 붙이지 않는다
- 주로 변수의 초기화에 사용된다.
class Display{
constructor(x=10,y=20){
this.x = x;
this.y = y;
console.log(this.x,this.y);
}
}
const display = new Display(100,200);
const display2 = new Display('이순신','최순실');
const display3 = new Display();
console.log(display.x);
console.log(display.y);
display.x = 1000;
console.log(display.x);
1-2 프로토타입 메서드
- 인스턴스를 통해서 호출 가능한 함수.
- 클래스 선언문 블록 내부에 선언하고, function을 붙이지 않는다
class Display{
foo(){
console.log(this,'foo 메서드 호출되었습니다');
}
foo2(x,y){
console.log(x,y,'foo2 메서드 호출되었습니다');
}
}
const display = new Display();
display.foo();
display.foo2('홍길동',200);
1-3 상속
- class 자식클래스 extends 부모클래스명{ }
class Parent{
constructor(){
console.log('부모 생성자 함수 호출');
}
}
class Son extends Parent{ // extends 뒤에 부모 클래스명을 작성한다
constructor(){
super(); // 부모 클래스의 생성자 함수 호출 없을시 에러
console.log('자식 생성자 함수 호출');
}
}
const parents = new Parent(); // '부모 생성자 함수 호출'
const son = new Son(); // '부모 생성자 함수 호출' ,'자식 생성자 함수 호출'
1-4 super() 키워드를 이용한 부모 클래스 메서드 호출
class Display{
constructor(x,y){
this.x = x;
this.y = y;
}
logPosition(){
console.log(this.x,this.y) // 100 200
}
}
class Son extends Display{
constructor(x,y,width,height){
super(x,y);
this.width = width;
this.height = height;
}
logScale(){
super.logPosition(); // 자식클래스 안에서 부모클래스의 함수를 호출할 시 super. 을 붙여준다
console.log(this.width,this.height); // 300 400
}
}
const son = new Son(100,200,300,400);
son.logScale();
son.logPosition(); // 외부에서 부모클래스의 함수를 호출할 때 자식클래스 의 함수로 호출이 가능하다.
console.log(son.x, son.y, son.width, son.height)
1-5 상속 예시
- 부모 클래스의 프로토타입 메서드명 과 자식 클래스의 프로토타입 메서드 명이 같을 때 호출시 자식 클래스의 메서드를 우선으로 호출한다.
- ex) 부모 클래스의 프로토타입 메서드는 전역, 자식클래스의 프로토타입 메서드는 지역 변수와 비슷한 맥락으로 사용된다.
class Animal{
constructor(){
console.log('동물입니다');
}
eat(){
console.log('먹기');
}
sound(){
console.log('소리');
}
}
class Dog extends Animal{
constructor(){
super();
}
sound(){
super.sound();
console.log('멍멍')
}
eat(){
super.eat();
console.log('사료')
};
guard(){
console.log('집지키기')
}
}
class Tiger extends Animal{
constructor(){
super();
}
sound(){
super.sound();
console.log('어흥');
}
eat(){
super.eat();
console.log('닭고기');
}
attack(){
console.log('사냥')
}
}
const dog = new Dog();
dog.sound();
dog.eat();
dog.guard();
const tiger = new Tiger();
tiger.sound();
tiger.eat();
tiger.attack();