Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

옥수수, 기록

ES6 class 문법 본문

카테고리 없음

ES6 class 문법

ok-soosoo 2022. 11. 21. 21:49

class 문법이란?

기존 생성자 함수, 프로토타입, 클로저를 사용해 객체 지향 프로그래밍을 구현하던 ES5와 다르게 ES6에서 class 키워드를 사용한 더 단순명료한 문법이 등장하였다. 그것이 바로 class 문법이다.

클래스 이름의 첫글자는 대문자를 사용하는게 일반적이다 (오류가 발생하지는 않는다)

class Computer {
  // constructor (생성자)
  constructor (monitor, speaker, internet, keyboard) { 
    // Computer에 속성부여
    this.monitor = monitor;
    this.speaker = speaker;
    this.internet = internet;
    this.keyboard = keyboard;
  }
  // 메서드 추가 생성
  Shouting() {
    console.log(`Im using ${this.monitor} monitor!`)
  }  
}
// 인스턴스 생성
const Mycom = new Computer('LG', 'Edifier', 'SKB', 'Logitec');
				// new Computer() 를 호출하게되면 Computer 클래스 내부에서 
                //	정의한 메서드가 들어 있는 새로운 객체가 생성된다.
                // 그리고 constructor가 자동으로 실행된다. 
                // 인수 'LG', 'Edifier', 'SKB', 'Logitec'이 차례대로 this.monitor...this.keyboard에 할당된다.
                    
Mycom.Shouting(); // Im using LG monitor!
// 위에서 Mycom에 Computer 내부의 메서드들(constructor(), Shouting())을 넣어놓았기 때문에
// Shouting() 메서드를 사용할 수 있는 것!

console.log(Mycom.__proto__ === Computer.prototype) // true

** 클래스는 클래스 선언문 이전에 참조할 수 없으며

 

class 란?

자바스크립트에서 class란 함수의 한 종류일 뿐 새로운 개체는 아니다.

class Human {
  constructor(name) { 
    this.name = name; 
  }
  
  sayHi() {`${this.name}`
  }
}

// User가 함수라는 증거
alert(typeof Human); // function

class Human {...} 문법 구조가 진짜 하는 일은

1. Human이라는 이름을 가진 함수를 만든다. 함수의 본문은 constructor 에서 가져오며 생성자 메서드가 없으면(constructor) 본문이 비워진 채로 함수가 만들어진다.

2. SayHi 같은 클래스 내에서 정의한 메서드Human.prototype에 저장한다.

 

let obj = new Human 으로 새로운 객체 obj를 만들고 메서드를 호출하면 메서드를 prototype 프로퍼티를 통해 가져온다.

class Human {
  constructor(name) { 
    this.name = name; 
  }
  
  sayHi() {`${this.name}`
  }
}

let obj = new Human(); // obj에 Human의 constructor(), sayHi()메서드가 들어있음

console.log(obj.__proto__) // Human {}

 

class Human의 선언 결과

클래스도 함수의 일종이기에 표현식으로 작성이 가능하다.

let Human = class {
	sayHi() {
      console.log('Hi');
  }
};


// class 표현식에 이름을 붙이면 함수표현식 내부에서만 사용할 수 있다.
let Human = class Insideclass {
	sayHi() {
      console.log('Hi');
  }
};

new Human().sayHi(); // 'Hi'
console.log(Insideclass); // ReferenceError

 

getter와 setter

get과 set을 사용해 obj.name을 조작할 수 있게 해보자

class Human {

  constructor(name) {
    // setter를 활성화합니다.
    this.name = name;
  }

// get(접근자) : 속성(.name)에 접근할 때 호출할 함수를 바인딩
  get name() {
    return this._name;
  }
  
}

let user = new Human("보라");
alert(user.name); // 보라 // get(접근자)에 의해 name속성에 접근할 때 get 함수 호출
				  // this._name이 리턴

 

get 구문은 객체의 속성 접근 시 호출할 함수를 바인딩하고

 

class Human {

  constructor(name) {
    // setter를 활성화합니다.
    this.name = name;
  }
// set 설정자 : 객체의 속성에 할당을 시도할 때 (ex constructor('minho')) 호출할 함수를 바인딩
   set name(value) {
 	 if (value.length < 4) {
 	   alert("이름이 너무 짧습니다.");
 	   return;
    }
    this._name = value;
  }

  
}

let user = new Human("보라");
user = new Human(""); // set(설정자)에 의해 name속성을 ""로 변경하려고 할 때 set 함수 호출
					  // 이름이 너무 짧습니다.

set 구문은 객체의 속성에 할당을 시도할 때 호출할 함수를 바인딩한다.

 

클래스 필드

클래스 필드(class field)라는 문법을 사용하면 어떤 종류의 속성(property)도 class에 추가할 수 있다.

class Human {
	name = "민수";
    
	sayHi() {
      console.log(`Hi ${this.name}`);
  }
};

new Human().sayHi(); // Hi 민수

위와 같이 속성이름 = <값>을 써주면 간단히 클래스 필드를 만들어 속성과 값을 추가할 수 있다.

다만 이렇게 할 경우 Human.prototype이 아닌 개별 객체에만 클래스 필드가 설정된다.

 

class Human {
	name = "민수";
    
  }
};

let human = new Human();
console.log(human.name); // "민수"
console.log(human.prototype.name); // undefined

 

 

참조사이트

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/set

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/get

https://ko.javascript.info/class

https://poiemaweb.com/es6-class

Comments