loading

새소식

Langauge/Javascript

[JS] 자바스크립트 클래스(Class) 개념

  • -
728x90
반응형

▶ Class  : 자료와 기능을 담는 템플릿

  1) 개념 

① 연관 있는 데이터를 한 곳에 묶어 놓는 컨테이너

② 전체적인 모습은 같지만 내부 구성요소 값은 다를 수 있음

class Person {
name; // 속성 (field)
age; // 속성 (field)
speak() {} // 행동 (method)
}
// Class 작성 방법 //
// 클래스 선언
class Rectangle {
// ...
}
// 클래스 표현식 (익명)
const Rect = class {
// ...
};
// 클래스 표현식 (이름 지정)
const rectange = class Rectangle {
// ...
};

   2) Class 작성 방법

// 클래스 선언
class Rectangle {
// ...
}
// 클래스 표현식 (익명)
const Rect = class {
// ...
};
// 클래스 표현식 (이름 지정)
const rectange = class Rectangle {
// ...
};

   3) 생성자

     - 객체 생성 시 속성 생성 또는 값을 할당 (초기화)

class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
const rectangle = new Rectangle(10, 20);
console.log(rectangle);
console.log(rectangle.height, rectangle.width);

  4) Getter / Setter

    - 속성에 값이 입력되거나 조회할 때 동작하는 기능

class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get height() {
return this._height;
}
set height(value) {
this._height = value;
}
}
const rectangle = new Rectangle(10, 20);
console.log(rectangle);
console.log(rectangle.height, rectangle.width);

  5) Method : 클래스 내의 함수

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(`${this.name}: hello!`);
}
}
const person = new Person('park', 30);
console.log(person.name);
console.log(person.age);
person.speak();

 

728x90
반응형
Contents

📝 포스팅 주소를 복사했습니다 📝

이 글이 도움이 되었다면 공감 부탁드립니다👍