🧐 같은 속성을 가졌지만 다른 데이터를 가진 객체를 여러 개 만들 수는 없을까?
👉🏼 쿠키 몰드를 사용해서 동일한 모양의 쿠키를 찍어낼 수 있는 것처럼,
객체(instance object)를 만들기 위한 쿠키 몰드가 있다면 어떨까?
👉🏼 여기에는 객체가 어떤 특징을 가질지(속성)와 어떤 동작/기능을 할지(메소드)를 포함해보자!
class를 활용해서 만들어진 객체
👉🏼 class 쿠키 몰을 사용해서 찍어낸 쿠키🍪
class Cookie{
//속성 지정하기
constructor(shape, flavor, color) {
//여기서 this는 Cookie를 의미함
this.shape = shape;
this.flavor = flavor;
this.color = color;
}
//메소드 지정하기
bake() {
console.log('쿠키를 굽습니다.');
};
eat() {
console.log('쿠키를 먹습니다.');
};
};
let cookie1 = new Cookie('round', 'chocoloate', 'brown');
let cookie2 = new Cookie('diamond', 'mint', 'sky-blue');
let cookie3 = new Cookie('heart', 'blueberry', 'purple');
//속성 사용하기
cookie1.shape; //'round'
cookie3.flavor; //'blueberry'
//메소드 사용하기
cookie1.bake(); //'쿠키를 굽습니다.'
cookie3.eat(); //'쿠키를 먹습니다.'
prototype
활용해서 메소드를 지정함prototype
: 모델의 청사진을 만들 때 쓰는 원형 객체(original form)function Cookie(shape, flavor, color) {
this.shape = shape;
this.flavor = flavor;
this.color = color;
}
//메소드 지정하기
Cookie.prototype.bake = function() {
console.log('쿠키를 굽습니다.');
}
Cookie.prototype.eat = function() {
console.log('쿠키를 먹습니다.');
}
class Cookie{
//속성 지정하기
constructor(shape, flavor, color) {
//여기서 this는 Cookie를 의미함
this.shape = shape;
this.flavor = flavor;
this.color = color;
}
//메소드 지정하기
bake() {
console.log('쿠키를 굽습니다.');
};
eat() {
console.log('쿠키를 먹습니다.');
};
};