[javascript] 클래스(class) 선언 / 상속 / 프라이빗
by mini_min[javascript] 클래스(class) 선언 / 상속 / 프라이빗
✔️ 클래스
: class는 객체를 생성하기 위한 템플릿이다.
: 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화한다.
: ES 2015 에서 도입된 클래스는 생성자의 기능을 대체한다. 클래스 표현식을 사용하면, 생성자와 같은 기능을 하는 함수를 훨씬 깔끔하게 문법으로 정의할 수 있다.
📓 선언
클래스는 클래스 표현식과 클래스 선언 두 가지 방법으로 정의할 수 있다.
: 함수로 호출할 수는 없다 ❌❌
: let const 처럼 블록 스코프에 선언한다.
: 메소드 안에서 super 키워드 사용이 가능하다.
: 클래스 선언은 호이스팅이 일어나지 않는다.
: 클래스를 사용하기 위해서는 클래스 먼저 선언해야한다.
❌ 클래스는 함수가 아니다.
❌ 클래스는 객체가 아니다.
📓 클래스 선언 방법
: 클래스를 선언하기 위해서는 클래스의 이름과 함께 class 키워드를 사용한다.
📓 클래스 표현식
: 클래스 표현식은 클래스를 정의하는 또 다른 방법이다.
: 표현식은 이름을 가질 수 있고, 갖지 않을수도 있다.
: 이름을 가진 class 표현식의 이름은 클래스 body 의 local scope 에 한해 유효하다.
name 속성으로 찾을 수 있다~
📓 클래스 몸체
: 클래스 몸체는 중괄호로 묶여 있는 안쪽 부분으로, 메소드나 constructor 와 같은 class 멤버를 정의한다.
: 본문은 strict mode 에서 실행된다.
📓 constructor (생성자)
: constructor 메소드는 class 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메소드이다.
클래스 안에 딱! 하나만 존재할 수 있다.
: 여러개 있으면 SyntaxError 발생
: 부모 클래스의 constructor 호출하기 위해 super 키워드 ✨ 사용이 가능하다.
📓 프로토타입 메소드
: 클래스의 메소드를 정의할 때는 객체 리터럴에서 사용하던 문법과 유사한 문법을 사용한다.
: getter , setter 정의하고 싶을 때는 메소드 이름 앞에 get 또는 set 을 붙이면 된다.
📓 인스턴스 속성
: 반드시 클래스 메소드 내에서 정의되어야한다.
class User { //클래스 안의 생성자 함수 : constructor 라는 이름으로 만든다. constructor({name, age}){ //필드 (생성자 안에 정의) this.name = name; this.age = age; } //메소드 sayHello() { return '안녕 내 이름은 ' + this.name + '이야!'; } }
const obj = new User({name:'홍길동', age:19}); console.log(obj.name); console.log(obj.sayHello());
console.log(typeof User); //function console.log(typeof User.prototype.constructor); //function console.log(typeof User.prototype.sayHello); //function console.log(obj instanceof User);
constructor 메소드에서 정의!!
💡 이름 : 홍길동 출력
: 안녕 내 이름은 홍길동이야! 출력된다.
-- 메소드 (1)
class Calc { add(x,y){ return x+y; } subtract(x,y){ return x-y; } } const obj = new Calc(); console.log(obj.add(10,5)); //15
-- 메소드 (2) 메소드 이름 설정
const methodName = 'sayName'; class User { constructor({name,age}){ this.name = name; this.age = age; } // 메소드 이름을 임의의 표현식을 대괄호로 둘러싸서 메소드 이름으로 사용 [methodName]() { return '나는 ' + this.name + ' 이다.'; } //메소드 안에서 반드시 this 필요함 } console.log(new User({name:'홍길동', age:20}).sayName() );
💡 메소드 이름을 [] 대괄호에 둘러싸서 임의의 표현식으로 사용할 수 있다~
-- 메소드 (3) getter, setter
class User { constructor() { this.name = ''; } get name() { return this._name; } set name(newName){ this._name = newName; } } const obj = new User(); obj.name = '홍길동'; console.log(obj.name);
💡 클래스.name = '홍길동' = setter 에서 newName 으로 '홍길동' 설정 (this._name)
name() 함수 사용했을 때, getter 에 의해 this._name 이 출력된다.
getter / setter 는 속성처럼 호출이 가능하다.
class Rect { constructor(width, height) { this.width = width; //10 this.height = height; //5 } calcArea() { // 메소드 return this.width * this.height; } get area() { //getter return this.calcArea(); } } const obj = new Rect(10,5); console.log(obj.area); //속성처럼 호출 가능
💡 getter 메소드를 호출하니, 안에서 calcArea() 메소드가 실행되어 결과가 추출되었다.
📓 정적 메소드와 속성
: static 키워드는 클래스를 위한 정적 메소드를 정의한다.
: 정적 메소드는 클래스의 인스턴스화 없이 호출되며, 클래스의 인스턴스에서는 호출 불가하다. ❌
: 보통 애플리케이션을 위한 유틸리티 함수를 생성하는데 주로 사용된다.
: 캐시, 환경설정, 인스턴스 간에 복제할 필요가 없는 기타 데이터에 유용하다.
class User { constructor(name, age){ this.name = name; this.age = age; } //this 사용 못함 static subject = '자바'; //정적인 필드 static result(score){ //정적인 메소드 return score >= 80? '우수' : '노력'; } } const obj = new User('가가가',20); //console.log(obj.subject); //에러 . static 속성은 객체로 접근 불가 console.log(User.subject); console.log(User.result(90));
💡 클래스 안에 static 필드와 static 메소드가 있는걸 볼 수 있다.
⭐⭐⭐ static 속성은 객체로 접근이 불가하다.
인스턴스화 없이 바로 호출이 가능하다.
console.log(User.subject);
console.log(User.result(90));
✔️ 클래스 상속
: 클래스 상속 기능을 통해 한 클래스의 기능을 다른 클래스에서 재사용할 수 있다.
: ⭐ extends 키워드는 클래스 선언이나 클래스 표현식에서 다른 클래스의 자식 클래스를 생성하기 위해 사용된다.
📓 super 키워드 통해 상위 클래스 호출
: 객체의 부모가 가지고 있는 메소드를 호출하기 위해 사용된다.
class Car { constructor(name) { this.name = name; } speed() { console.log(this.name + ": 시속 80 " ) } color() { console.log(this.name + ": 검정색") } } class Taxi extends Car { constructor(name) { super(name); // super class 생성자 호출 } //재정의 speed() { super.speed(); console.log(this.name + ": 시속 100"); } } const t = new Taxi('그랜저'); t.speed(); t.color();
💡 Taxi 클래스에서 상위 클래스 생성자를 호출했고, 상위 클래스의 메소드를 재정의했다. (speed)
재정의한 speed 와 기존 speed 메소드가 각각 호출된다.
✔️ 클래스 프라이빗 속성
: # 은 프라이빗 속성이다.
//static private static #A; // instance private #B;
constructor() { this.#B =100; } static fun() { User.#A = 10; return User.#A; } sub() { return this.#B; }
블로그의 정보
개발자 미니민의 개발로그
mini_min