JS/Javascript

[Javascript] 클래스

ui-o 2023. 11. 7. 16:31
반응형

클래스

  • 객체 지향 프로그래밍언어에서  객체를 효율적으로 사용가능하게  하는 문법
  • 추상화 : 프로그램에서 필요한 요소만을 사용하여 객체를 표현하는 것 
  • 객체 지향 프로그래밍 : 객체들을 정의하고 객체를 활용하여 프로그램을 만드는 것
  • 인스턴스(객체) : 클래스를 기반으로 생성한 객체

클래스 생성

  • 클래스를 기반으로 만든 객체를 기본적으로 인스턴스(객체)라고 부름
// [형식] 클래스 생성
class 클래스명 { // 클래스명은 대문자로 시작

}

// 클래스 생성 [형식]
const temp = new 클래스명

생성자 (Constructor)

  • 객첼를 초기화하고 클래스의 속성을 설정
  • 객체가 클래스로 부터 생성될 때 자동으로 호출
  • 생성자 이름은 항상 constructor로 정의

생성자의 주요역할

1. 객체 초기화 : 클래스로부터 객체의 초기 상태를 정의

2. 속성 초기화 : 주로 생성자 내에서 객체의 속성(멤버 변수)을 초기화

3. 매개변수 처리 : 객체 생성 시 전달된 매개변수(인수)를 받아 객체의 속성값을 정의

4. 상위 클래스 호출 : 상속관계에서 하위 클래스의 생성자에서 상위 클래스의 생성자를 호출하여 상위 클래스의 초기화 코드 실행 가능 - super 키워드를 사용하여 수행

 

// [형식]
class 클래스명 {
	constructor(){
    	// 생성자 코드
    }
}

// [형식] 생성자  호출
new 클래스명()

getter / setter 메소드

  • getter메소드 : 속성 값 확인
  • setter 메소드 : 속성 값 설정
  • 속성을 사용, 설정하는 형태로 사용하면 자동으로 getter와 setter를 구분하여 호출됨
// [형식]
class 클래스명{
 // getter
 get 이름 () {
 	return '메시지'
 }
 
 // setter
 set 이름(value) {
 	// 설정값
 }

}


// (예)
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  get info() {
    return console.log(this.name);
  }

  set info2(name) {
    this.name = name;a
  }
}

const person = new Person('John, 20');

console.log(person);

person.info;

person.info2('Jane');

 클래스 기본 활용

  • 기본 활용 예
class Person {
  // 생성자
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // 메서드
  printInfo() {
    return console.log(this.name + '' + this.age);
  }
}

// 객체 선언
const list = [];
list.push(new Person('Jane', 20));
list.push(new Person('John', 24));


// 메서드 실행
let res = '';
list.forEach((e) => {
	console.log(e);
  e.printInfo();
});

클래스 상속

  • 클래스 상속 시 따로 부모 클래스의 메소드를 그대로 활용 가능
  • super() : 부모의 생성자 함수를 나타냄, 부모의 생성자 함수의 속성을 그대로 가져올 수 있음
// [형식]
class 클래스명 extends 부모 클래스 {
	
}

 Sources

  • 기본 활용 예
class Rect  {
	constructor (w, h) {
		this.w =w
		this.h =h
	}

	getSize() {
		return this.w * this.h
	}
}

const rect = new Rect(10, 20);


class Square extends Rect {
	constructor(length) {
		super(length, length) // 부모생성자 함수를 호출
	}
}

// 클래스 사용
const square= new Square(10,20)
console.log(square.getSize()); // 100

private 속성과 메소드

  • 클래스 내부에서만 접근 가능한 속성과 메소드
  • 선언된 클래스 활용 시 의도한 대로 사용을 유지하도록 이름에 #을 붙여 구분하는 법
  • private 속성 선언시 클래스 외부에서 해당 메소드 접근 불가
//  [형식]
class 클래스명 {
	#속성이름
    #메소드 이름() {}
}
// 활용 예
class Square {
  #length;

  constructor(length) {
    this.#length = length;
  }

  printLength() {
    console.log(this.#length);
  }
}

const square = new Square(10);

square.printLength(); // 10

static 속성과 메소드

  • 디자인 패턴 활욜을 위해 사용되는 정적 속성과 메소드
  • 인스턴스를 만들지 않고 사용 가능
class 클래스 이름 {
	static 속성 = 값
	static 메소드 () {}

}
  • 점을 사용하여 속성과 메소드에 접근 가능
클래스 이름.속성
클래스 이름.메소드
// [exam]
class Square {
  #length;
  // static 속성 선언
  static #counter = 0; // private 속서과 static 속성의 경우 동시 적용 가능
  static get counter() {
    return Square.#counter;
  }

  // 생성자
  constructor(length) {
    this.length = length;

    Square.#counter += 1;
  }

  // static 메소드
  static primeterOf(length) {
    return length * 4;
  }

  static areaOf(length) {
    return length * length;
  }

  get length() {
    return this.#length;
  }

  get primeter() {
    return this.#length * 4;
  }

  get area() {
    return this.#length * this.#length;
  }

  set length(length) {
    if (length <= 0) {
      throw '0보다 커야 함';
    }
    this.#length = length;
  }
}

// static 속서 사용
const squareA = new Square(10),
  squareB = new Square(20),
  squareC = new Square(30);

console.log(`counter : ${Square.counter}`);
console.log(`primeterOf : ${Square.primeterOf(20)}`);

 


Override

  • 부모가 가지고 있는 함수와 동일한 함수명으로 선언하여 덮어씌우는 방식
// [Exam]
class LifeCycle {
  call() {
    this.a();
    this.b();
    this.c();
  }

  a() {
    console.log('a()');
  }
  b() {
    console.log('b()');
  }
  c() {
    console.log('c()');
  }
}

// 인스턴스 생성
new LifeCycle().call(); // ⇒ a() b()  c()

// 자식 클래스 선언
class Cycle extends LifeCycle {
  // 함수 오버라이드
  a() {
    console.log('child of a()');

    // 부모의 메소드 내용 사용하는 경우
    super.a();
  }
}

new Cycle().call(); // ⇒ child of a() a() b() c()

 

toString() 오버라이드

  • 자바스크립트 Object(숫자, 문자열, 불, 배열, 함수, 클래스, 클래스의인스턴스)는 toString() 메소드를 가짐
  • 이를 통해 클래스 생성 시 Object클래스를 상속받게 되어 toString메소드를 오버라이드 하여 사용 가능
  •  
// [Exam]
class Pet {
	constructor(name, age) {
		this.name = name
		this.age = age
	}

	toString(){
		return `name : ${this.name} , age: ${this.age}`
	}
}

const pet = new Pet('c',4)
console.log(pet);

 

반응형