JavaScript

javaScript-ES6 classes

용용it 2023. 7. 14. 22:53

ES6에서 도입된 클래스는 객체를 생성하기 위한 템플릿이다.

클래스를 사용하면 객체 지향 프로그래밍의 개념을 더욱 편리하게 활용할 수 있다.

 

기본 구조이다.

class ClassName {
  constructor() {
    // 생성자 메서드
  }

  method1() {
    // 메서드 1
  }

  method2() {
    // 메서드 2
  }
  
  // ...
}

여기서 ClassName은 클래스 이름이고 

constructor는 클래스의 생성자 메서드로, 객체가 생성될 때 자동으로 호출된다.

생성자 메서드 내에서는 객체의 초기화를 수행하고 필요한 속성을 설정할 수 있다.

 

 

 

클래스를 사용하여 객체를 생성하는 방법.

const obj = new ClassName();

new 키워드를 사용하여 ClassName을 호출하면 

ClassName의 생성자 메서드가 실행되고 새로운 객체가 생성된다.

 

 

 

예시

class User {
	constructor(first, last) {
 		this.firstName = first   
        this.lastName = last
    }
    getFullName() {
    	return `${this.firstName} ${this.lastName}`
    }
}

const dragon = new User('Dragon','Lee')
const james = new User('James','Raynor')

console.log(dragon.getFullName())  // Dragon Lee
console.log(james.getFullName()) // James Raynor

 

'JavaScript' 카테고리의 다른 글

javaScript- 날짜  (0) 2023.07.27
카테고리 별로 분류  (0) 2023.07.27
javaScript-prototype  (0) 2023.07.12
javaScript-호출 스케줄링  (0) 2023.07.05
javaScript-함수 객체의 프로퍼티  (0) 2023.04.15