JavaScript에서의 클래스 문법은 객체지향 프로그래밍(OOP)을 지원하기 위해 도입된 문법입니다. ES6(ECMAScript 2015)부터 제공되며, 객체 생성 및 관리가 더 직관적이고 명확하게 표현됩니다. 주요 개념은 다음과 같습니다.
예시
javascript
코드 복사
class Person {
constructor(name, age) {
this.name = name; // 속성 정의
this.age = age;
}
greet() { // 메서드 정의
console.log(`Hello, my name is ${this.name}`);
}
}
예시
javascript
코드 복사
const person1 = new Person("Alice", 25);
person1.greet(); // Hello, my name is Alice
예시
javascript
코드 복사
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
}
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.brand); // Toyota
예시
javascript
코드 복사
class Account {
constructor(balance) {
this._balance = balance; // private-like 변수
}
get balance() { // Getter
return this._balance;
}
set balance(value) { // Setter
if (value < 0) {
throw new Error("Balance cannot be negative");
}
this._balance = value;
}
}
const account = new Account(1000);
console.log(account.balance); // 1000
account.balance = 500; // Setter 호출
console.log(account.balance); // 500
예시
javascript
코드 복사
class Animal {
speak() {
console.log("Animal speaks");
}
}
class Dog extends Animal { // Animal을 상속
speak() {
console.log("Woof!");
}
}
const dog = new Dog();
dog.speak(); // Woof!
예시
javascript
코드 복사
class MathOperations {
static add(a, b) {
return a + b;
}
}
console.log(MathOperations.add(5, 3)); // 8
예시
javascript
코드 복사
class Employee {
#salary; // Private field
constructor(name, salary) {
this.name = name;
this.#salary = salary;
}
getSalary() {
return this.#salary; // Private field 접근
}
}
const emp = new Employee("Bob", 50000);
console.log(emp.getSalary()); // 50000
// console.log(emp.#salary); // 에러: Private field는 외부에서 접근 불가
예시
javascript
코드 복사
class User {
name = "Default"; // 클래스 필드
greet() {
console.log(`Hello, ${this.name}`);
}
}
const user = new User();
user.greet(); // Hello, Default
예시
javascript
코드 복사
class Shape {
draw() {
console.log("Drawing a shape");
}
}
class Circle extends Shape {
draw() {
console.log("Drawing a circle");
}
}
class Square extends Shape {
draw() {
console.log("Drawing a square");
}
}
const shapes = [new Shape(), new Circle(), new Square()];
shapes.forEach(shape => shape.draw());
// Output:
// Drawing a shape
// Drawing a circle
// Drawing a square
예시
javascript
코드 복사
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello from ${this.name}`);
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 부모 생성자 호출
this.age = age;
}
greet() {
super.greet(); // 부모 메서드 호출
console.log(`I am ${this.age} years old`);
}
}
const child = new Child("Alice", 10);
child.greet();
// Output:
// Hello from Alice
// I am 10 years old
이 모든 개념은 JavaScript에서 객체지향 프로그래밍(OOP)을 구현하는 데 사용되며, 재사용성, 유지보수성, 코드 가독성을 높이는 데 유용합니다.