JavaScript의 객체 지향 프로그래밍(OOP)

Mar 16 2023
OOP(개체 지향 프로그래밍)는 코드를 서로 상호 작용할 수 있는 개체로 구성하는 것과 관련된 프로그래밍 패러다임입니다. JavaScript는 OOP를 지원하는 언어이며, 이 기사에서는 이러한 개념을 설명하는 데 도움이 되는 예제와 함께 JavaScript에서 OOP의 몇 가지 주요 개념을 살펴보겠습니다.

OOP(개체 지향 프로그래밍)는 코드를 서로 상호 작용할 수 있는 개체로 구성하는 것과 관련된 프로그래밍 패러다임입니다. JavaScript는 OOP를 지원하는 언어이며, 이 기사에서는 이러한 개념을 설명하는 데 도움이 되는 예제와 함께 JavaScript에서 OOP의 몇 가지 주요 개념을 살펴보겠습니다.

JavaScript의 객체 지향 프로그래밍

자바스크립트의 객체

JavaScript에서 객체는 속성 모음이며 각 속성은 키-값 쌍입니다. 키는 속성의 이름을 나타내는 문자열이며 값은 다른 개체를 포함하여 모든 데이터 유형이 될 수 있습니다.

다음은 JavaScript에서 객체의 예입니다.

const person = {
  name: 'Brendan Eich',
  age: 60,
  address: {
    street: '123 JavaScript Street',
    city: 'Web',
    state: 'Programming',
    zip: '12345'
  }
};

점 표기법이나 대괄호 표기법을 사용하여 객체의 속성에 액세스할 수 있습니다.

console.log(person.name); // Output: 'Brendan Eich'
console.log(person['age']); // Output: 60
console.log(person.address.city); // Output: 'Web'

OOP에서 클래스는 객체 생성을 위한 청사진입니다. 해당 클래스의 개체가 갖게 될 속성과 메서드를 정의합니다. JavaScript에서는 class키워드를 사용하여 클래스를 정의할 수 있습니다.

다음은 클래스의 예입니다 Person.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

클래스 의 객체를 생성하기 위해 다음 키워드를 Person사용합니다 new.

const person = new Person('Brendan Eich', 60);
person.greet(); // Output: 'Hello, my name is Brendan Eich and I am 60 years old.'

상속은 기존 클래스를 기반으로 새 클래스를 만드는 프로세스입니다. 하위 클래스로 알려진 새 클래스는 수퍼 클래스로 알려진 기존 클래스의 속성과 메서드를 상속합니다.

JavaScript에서는 extends키워드를 사용하여 상속을 구현할 수 있습니다. 예를 들면 다음과 같습니다.

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  study() {
    console.log(`${this.name} is a ${this.grade} in JavaScript.`);
  }
}

클래스 의 객체를 생성하기 위해 다음 키워드를 Student사용합니다 new.

const student = new Student('Sumit', 38, 'beginner');
student.greet(); // Output: 'Hello, my name is Sumit and I am 38 years old.'
student.study(); // Output: 'Sumit is a beginner in JavaScript.'

JavaScript의 캡슐화

캡슐화는 개체의 내부 세부 정보를 숨기고 개체와 상호 작용할 수 있는 공용 인터페이스를 제공하는 방법입니다. 이렇게 하면 외부 코드가 개체의 내부 상태를 직접 수정하여 버그 및 기타 문제를 일으킬 수 있는 것을 방지할 수 있습니다. JavaScript에서는 클로저를 사용하여 캡슐화를 달성할 수 있습니다. 예를 들면 다음과 같습니다.

function createCounter() {
  let count = 0;

  return {
    increment() {
      count++;
    },

    decrement() {
      count--;
    },

    getCount() {
      return count;
    }
  };
}

const counter = createCounter();
console.log(counter.getCount()); // Output: 0
counter.increment();
console.log(counter.getCount()); // Output: 1
counter.decrement();
console.log(counter.getCount()); // Output: 0

JavaScript의 다형성

다형성은 서로 다른 클래스의 개체가 같은 클래스의 개체인 것처럼 취급되는 기능입니다. JavaScript에서는 인터페이스를 사용하여 다형성을 달성할 수 있습니다.

예를 들면 다음과 같습니다.

class Shape {
  draw() {
    console.log('Drawing shape...');
  }
}

class Circle extends Shape {
  draw() {
    console.log('Drawing circle...');
  }
}

class Square extends Shape {
  draw() {
    console.log('Drawing square...');
  }
}

function drawShapes(shapes) {
  shapes.forEach(shape => {
    shape.draw();
  });
}

const shapes = [
  new Circle(),
  new Square(),
  new Circle(),
  new Square()
];

drawShapes(shapes);

drawShapes그런 다음 개체 배열을 사용 Shape하고 해당 메서드를 호출하는 함수를 정의합니다 draw. Circle객체 의 배열을 만들어 Square함수에 전달합니다 drawShapes. 개체가 다른 클래스에 속하더라도 동일한 클래스의 개체인 것처럼 취급할 수 있음을 알 수 있습니다 Shape.

중요한 예

다음은 JavaScript의 개체, 클래스, 상속 및 다형성을 보여주는 예입니다.

// define a base class called Animal
class Animal {
  constructor(name) {
    this.name = name;
  }

  eat() {
    console.log(`${this.name} is eating.`);
  }

  sleep() {
    console.log(`${this.name} is sleeping.`);
  }
}

// define a subclass called Cat that inherits from Animal
class Cat extends Animal {
  constructor(name) {
    super(name);
  }

  meow() {
    console.log(`${this.name} says meow.`);
  }

  // override the sleep method of Animal
  sleep() {
    console.log(`${this.name} is taking a cat nap.`);
  }
}

// define another subclass called Dog that also inherits from Animal
class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  bark() {
    console.log(`${this.name} says woof.`);
  }

  // override the eat method of Animal
  eat() {
    console.log(`${this.name} is eating from a bowl.`);
  }
}

// create an array of animals
let animals = [
  new Cat("Mumu"),
  new Dog("Laltu"),
  new Cat("Miaow"),
  new Dog("Boltu")
];

// loop through the array and call methods on each animal
for (let animal of animals) {
  animal.eat();
  animal.sleep();

  // check if the animal is a cat and call the meow method if it is
  if (animal instanceof Cat) {
    animal.meow();
  }

  // check if the animal is a dog and call the bark method if it is
  if (animal instanceof Dog) {
    animal.bark();
  }
}

Cat그런 다음 두 개의 하위 클래스 및 를 정의합니다 Dog. 이 두 클래스는 모두 키워드를 Animal사용하여 상속됩니다 extends. 그들은 또한 부모 클래스 를 호출하고 인스턴스 변수를 설정하기 위해 호출하는 자체 constructor메서드를 가지고 있습니다 .superconstructorname

이 Cat클래스에는 meow콘솔에 메시지를 출력하는 메서드가 있으며 sleep부모 클래스의 메서드도 재정의합니다. 이 Dog클래스에는 bark콘솔에 메시지를 출력하는 메서드가 있으며 eat부모 클래스의 메서드도 재정의합니다.

그런 다음 및 개체를 Animal모두 포함하는 개체 배열을 만듭니다 . 배열을 반복하고 각 개체에서 및 메서드를 호출합니다. 또한 연산자를 사용하여 각 개체가 또는 의 인스턴스인지 확인 하고 적절한 메서드( 개체 및 개체 )를 호출합니다.CatDogeatsleepinstanceofCatDogmeowCatbarkDog

이는 JavaScript에서 개체, 클래스, 상속 및 다형성을 사용하여 재사용 가능하고 확장 가능한 코드를 만드는 방법을 보여줍니다.

결론

이 기사에서는 객체, 클래스, 상속, 캡슐화 및 다형성을 포함하여 JavaScript에서 OOP의 핵심 개념 중 일부를 살펴보았습니다. 이러한 개념과 이를 사용하는 방법을 이해하면 JavaScript 애플리케이션에서 유지 관리 및 재사용 가능한 코드를 더 많이 작성할 수 있습니다.