

프로퍼티(변수) 와 메소드 (함수) 로 이루어진 각 객체들의 상호 작용을 중심으로 코드를 작성하는 것.
(참고: 절차 지향 프로그래밍? 변수와 함수를 가지고 작업의 순서에 맞게 코드를 작성하는 것→ 이전 방법)
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로 객체를 생성하여 리턴하는 방법
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를 붙여서 실행해야 한다는 사실
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 밖에 정의