JavaScript: 객체를 생성하는 세 가지 방법

MARCOIN·2022년 6월 2일
0

개인적인 공부 기록

목록 보기
10/11

1. 객체지향 프로그래밍

Property와 Method로 이루어진 각 객체들의 상호작용을 중심으로 코드를 작성하는 것


2. JS에서 객체를 생성하는 방법

2-1. Object literal과 Factory function 사용

function createUser(name, email){
    const user = {
        name,
        email,

        print(){
            console.log(`${this.name}의 이메일은 ${this.email} 입니다.`);
        }
    }
    return user;
}

const user1 = createUser('해리', 'harry@hogwarts.com');
user1.print();
  • Factory Function: 객체를 생성
  • Object literal로 객체를 생성하고 리턴하는 방법

2-2. Constructor Function 사용

function User (name, email){
    this.name = name;
    this.email = email;
    this.print = ()=>{
        console.log(`${this.name}의 이메일은 ${this.email} 입니다.`);
    }
}

const user1 = new User('해리', 'harry@hogwarts.com');
user1.print();
  • Constructor Function: 객체를 생성하는 용도로 사용하는 함수
  • 함수 안에서 this 키워드를 사용하여 생성될 객체의 property와 method를 정의 및 설정
  • 객체 생성 시 new를 붙여서 실행해야함

2-3. class 사용

class User {
    constructor(name, email){
        this.email = email;
        this.name = name;
    }
    print(){
        console.log(`${this.name}의 이메일은 ${this.email} 입니다.`);
    }
}

const user1 = new User('해리', 'harry@hogwarts.com');
user1.print();
  • Class 키워드를 사용해서 객체의 틀을 정의
  • 객체 생성 시 new를 붙여서 생성해야함
  • Property의 경우 constructor 안에 정의 (객체가 생성될 때 자동으로 실행)
profile
공부하는 기획자 👀

0개의 댓글