TIL 28 | 객체 지향 프로그래밍

CHAEIN·2021년 7월 19일
0

JavaScript

목록 보기
24/31
post-thumbnail

객체 지향 프로그래밍이란

'객체' 간의 상호작용을 중심으로 하는 프로그래밍을 의미한다. 여기서 '객체'에는 객체의 상태를 나타내는 '변수'와 객체의 행동을 나타내는 '함수'가 들어있다. 객체안의 변수는 property(속성)라고 하고 객체안의 함수는 method(메소드)라고 한다. 이에 따라 객체 지향 프로그래밍은 프로퍼티와 메소드로 이루어진 각 객체들의 상호작용을 중심으로 코드를 작성하는 것이다.

객체지향 프로그래밍에선 하나의 모델이 되는 청사진(constructor function , class 등)을 만들고 그 청사진을 바탕으로 객체를 생성해 프로그래밍하는 데 이처럼 청사진을 바탕으로 생성된 객체를 인스턴스(instance)라고 부른다.

객체를 만드는 방법

(1) Object Literal

중괄호를 사용하여 객체를 생성하는 방법이다.

const user = {
  email: 'hi@google.com',
  birthdate: '2000-10-10',
  buy(item){
    console.log(`${this.email} buys ${item.name}`)
  }
}

const item = {
  name : '원피스'
}

console.log(user.email) // 'hi@google.com'
console.log(user.birthdate) // '2000-10-10'
user.buy(item) // hi@google.com buys 원피스

(2) Factory function

Object Literal 방식으로만 생성된 객체는 재사용이 불가능하다. 같은 속성에 값만 다른 객체가 필요해도 비슷한 형태의 객체를 계속 다시 만들어 사용해야한다. 이 때 Factory function을 사용하면 Object Literal 방식에 재사용성을 추가할 수 있다.

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

// createUser 함수를 이용하여 형태는 동일하지만 값이 다른 객체 생성
const user1 = createUser('djfs@sjdfd.com', '1999-09-09')
const uwer2 = createUser('sfsds@dfgdf.net', '2010-02-02')

(3) Constructor function

//constructor function의 이름 첫글자는 대문자로 작성한다. 
function User(email, birthdate){
  this.email = email; // this는 생성될 객체, 인스턴스를 가리킨다. 
  this.birthdate = birthdate;
  this.buy = function(item){
    console.log(`${this.email} buys ${item.name})
  }
}

// constructor function으로 객체를 생성하려면 new를 붙여야한다. 
const user1 = new User('djfs@sjdfd.com', '1999-09-09')

(4) Class

class User{
  // 속성은 constructor 함수 내부에
  constructor(email, birthdate){
    this.email = email;
    this.birthdate = birthdate;
  } 
  
  // 메소드는 constructor 함수 바깥에 
  buy(item){
    console.log(`${this.email} buys ${item.name}`)
  }
}

const user1 = new User('djfs@sjdfd.com', '1999-09-09')

0개의 댓글