[JavaScript]자바스크립트 객체 지향 기본기

grace·2022년 11월 22일

javascript

목록 보기
4/4
post-thumbnail

객체란?


객체 지향 프로그래밍이란?

프로퍼티(변수) 와 메소드 (함수) 로 이루어진 각 객체들의 상호 작용을 중심으로 코드를 작성하는 것.
(참고: 절차 지향 프로그래밍? 변수와 함수를 가지고 작업의 순서에 맞게 코드를 작성하는 것→ 이전 방법)

  • 추상화 : 어떤 구체적인 존재를 원하는 방향으로 간략화해서 나타내는 것
  • 캡슐화 : 특정 프로퍼티에 대한 접근을 미리 정해진 메소드를 통해서만 가능하도록 하는 것
  • 상속 : 부모 클래스의 프로퍼티와 메소드를 자식 클래스가 그대로 물려받는 것
  • 다형성 : 하나의 변수가 다양한 종류의 클래스로 만든 여러 객체를 가리킬 수 있음

1. Object literal(객체를 나타내는 문자열) 과 Factory function 사용하기

function createUser(email, birthdate) {
  const user = {
    email,
    birthdate,
    buy(item) {
      console.log(`${this.email} buys ${item.name}`);
    },
  };
  return user;
}

const user1 = createUser('chris123@google.com', '19920321');
const user2 = createUser('jerry99@google.com', '19950719');
const user3 = createUser('alice@google.com', '19931224');

객체를 생성하는 Factory function을 만들고, 그 안에서 Object literal로 객체를 생성하여 리턴하는 방법

2. Constructor function (생성자 함수)사용하기

function User(email, birthdate) {
  this.email = email;
  this.birthdate = birthdate;
  this.buy = function (item) {
    console.log(`${this.email} buys ${item.name}`);
  };
}

const user1 = new User('chris123@google.com', '1992-03-21');
const user2 = new User('jerry99@google.com', '1995-07-19');
const user3 = new User('alice@google.com', '1993-12-24');

객체를 생성하는 용도로 사용하는 Constructor function을 정의하고,
그 안에서 this 키워드를 사용하여 생성될 객체의 프로퍼티와 메소드를 설정하는 방법
Constructor function으로 객체를 생성하려면 그 앞에 new를 붙여서 실행해야 한다는 사실

3. class 키워드 사용하기

class User {
  constructor(email, birthdate) { //constructor 생성사 메소드는 객체가 생설될때 실행됨
    this.email = email; //this는 생성되는 객체로 매번 생성되는 새로운 객체의 프로퍼티 값이 된다.
    this.birthdate = birthdate;
  }

  buy(item) {
    console.log(`${this.email} buys ${item.name}`);
  } // 이 부분이 해당 객체의 메소드
}

const user1 = new User('chris123@google.com', '1992-03-21');
const user2 = new User('jerry99@google.com', '1995-07-19');
const user3 = new User('alice@google.com', '1993-12-24');

class 키워드를 사용해서 객체의 틀을 정의하고, 마찬가지로 그 앞에 new를 붙여서 객체를 생성하는 방법
class를 사용할 때는 보통 프로퍼티의 경우 constructor 안에 정의하고, 메소드의 경우 constructor 밖에 정의

profile
미래의 개발자!

0개의 댓글