Javascript [ Class ]

양혜정·2024년 4월 7일
1

javascript_web

목록 보기
23/81

Class

  • ES6(ECMAScript 6)

문법

class ClassName{
	속성명 = 초기값;			// 초기값 설정
	constructor() {...}		// 생성자 함수
    // === Setter === //
    set xxx(value) {
    	this.속성명 = value;
    }
    // === Getter === //
    get xxx(){return this.속성명;}
    // === method === //
    method(){...}
}

초기값 설정 ( 속성명 )

  • public
    외부에서도 접근 가능
속성명 = 0;
  • private
    클래스안에서만 접근 가능
#속성명 = 0;

생성자 함수

  • 자바는 필드가 다 선언되야 생성자 함수의 사용 가능하지만, 자바스크립트는 생성자에 넣어주면 자동적으로 선언되어진다.
constructor(필드명1,필드명2){
	this.필드명1 = 필드명1;
  	this.필드명2 = 필드명2;
}

Setter

set set속성명(value){	// 이때 속성명의 맨 앞의 글자는 대문자
  	...
    this.#속성명 = value;
}

Getter

get get속성명(){		// 이때 속성명의 맨 앞의 글자는 대문자
	return this.#속성명;
}

주의사항

  • Setter

Setter 주의

잘못된 경우 => 객체.set속성명(value);
올바른 방법 => 객체.set속성명 = "value";

  • Getter

Getter 주의

잘못된 경우 => 객체.get속성명()
올바른 방법 => 객체.get속성명


Method

// 함수 선언
함수명(){
	const currentDate = new Date();		// 현재 날짜 시간
  	// currentDate.getFullYear() : 현재 년도
  	return currentDate.getFullYear() - this.#속성명 + 1;	// 나이
}

정리

  • 09javascriptStandardObject -> 01_Array_class
    -> 06
    객체배열class사용_selectedIndex.html, 06.css, 06.js

0개의 댓글

관련 채용 정보