JavaScript의 클래스(Class)는 객체 지향 프로그래밍의 특징을 사용할 수 있는 방법을 제공합니다. 클래스는 객체의 특성과 기능을 캡슐화하고, 객체를 생성하는 "틀" 역할을 합니다. ES6부터 JavaScript에 공식적으로 클래스 문법이 도입되었습니다.
클래스 선언
클래스를 선언하기 위해서는 class 키워드를 사용합니다. 다음은 간단한 클래스 선언 예시입니다:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<script>
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
alert(`Hello, my name is ${this.name}! and my age is ${this.age}`);
}
}
const john = new Person("john", 25);
john.greet();
</script>
</body>
</html>
생성자 함수
constructor 메서드는 클래스의 인스턴스를 생성하고 초기화할 때 호출됩니다. 위 예제에서 name과 age는 생성자의 매개변수로 전달되어 인스턴스의 속성으로 저장됩니다.
인스턴스 생성
new 키워드를 사용하여 클래스의 인스턴스를 생성할 수 있습니다:
const john = new Person('John', 25);
john.greet(); // Hello, my name is John!
상속
extends 키워드를 사용하여 클래스간의 상속을 구현할 수 있습니다:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<script>
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
alert(`Hello, my name is ${this.name}! and my age is ${this.age}`);
}
}
const john = new Person("john", 25);
john.greet();
class student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
greet() {
alert(
`Hello, my name is ${this.name}! and my age is ${this.age} and my grade is ${this.grade}`
);
}
}
const alie = new student("alie", 25, "3rd");
alie.greet();
</script>
</body>
</html>
※super 키워드는 자바스크립트 클래스에서 부모 클래스의 생성자나 메서드를 참조할 때 사용됩니다. 이 키워드는 주로 상속과 관련된 상황에서 사용되며, 서브클래스에서 부모 클래스의 기능을 재사용하거나 확장할 때 유용합니다.
Getter와 Setter
get과 set 키워드를 사용하여 속성에 대한 접근자와 설정자를 정의할 수 있습니다:
class Circle {
constructor(radius) {
this._radius = radius;
}
get radius() {
return this._radius;
}
set radius(value) {
if (value < 0) {
console.log('Radius cannot be negative');
} else {
this._radius = value;
}
}
}
const circle = new Circle(5);
console.log(circle.radius); // 5
circle.radius = -1; // Radius cannot be negative
'JavaScript' 카테고리의 다른 글
JavaScript JSON (0) | 2023.08.23 |
---|---|
JavaScript Modules ES6 모듈 (0) | 2023.08.23 |
JavaScript 화살표 함수(Arrow Function) (0) | 2023.08.23 |
JavaScript use strict(strict mode) (0) | 2023.08.23 |
JavaScript 호이스팅(hoisting) (0) | 2023.08.23 |