const person1 = { name: 'bob', age: 2};
const person2 = { name: 'steve', age: 3};
const person3 = { name: 'dave', age: 4};
→ 객체마다 다른 값을 선언하려면 key 값을 반복해서 작성해야하는 번거러움이 있다.
방법은 두 가지로 'function' 함수로 만들거나 'class' 로 만들어 호출하는 방식이다.
예전 JavaScript에서는 function을 이용하여 constructor function을 만들었지만 ES6 이후 class가 생겨나고 나서부터는 class 를 선언하여 객체를 생성한다.
function makePerson(name, age) {
return {
name, // name = name;
age, // age = age;
};
}
const person4 = makePerson('ht', 28);
console.log(person4); // {name: "ht", age: 28}
function Person(name, age) {
// this = {};
this.name = name;
this.age = age;
// return this;
}
const person5 = new Person('ellie', 30);
console.log(person5); // Person {name: "ellie", age: 30}
class CoffeeMaker {
// 멤버변수
static BEANS_GRANS_PER_SHOT = 7; // class level
coffeeBeans = 0; // instance (object) level
// 생성자 함수
constructor(coffeeBeans) {
this.coffeeBeans = coffeeBeans;
}
// 멤버함수(메소드)
makeCoffee(shots) {
if (this.coffeeBeans < shots * CoffeeMaker.BEANS_GRANS_PER_SHOT) {
throw new Error('Not enough coffee beans!');
}
this.coffeeBeans -= shots * CoffeeMaker.BEANS_GRANS_PER_SHOT;
return {
shots: shots,
hasMilk: false,
}
}
}
const maker = new CoffeeMaker(34);
console.log(maker); // CoffeeMaker {coffeeBeans: 34}
// [ 객체 구분 ]
// 1. 일반 객체
const foo1 = {
name: "Hxx",
};
// -------------------------
// 2. 함수
const foo2 = function () {
const name = "Hxx";
};
// -------------------------
// 3. 생성자 함수
function Foo3() {
// this = {}
this.name = "Hxx";
// return this
};
// 3-1. 생성자 함수 객체
const foo3 = new Foo3();
// -------------------------
// 4. 클래스 함수
class Foo4 {
// 멤버변수
name = "Hxx";
age = 0;
// 생성자 함수
constructor(age) {
this.age = age;
}
// 멤버함수(메소드)
studentData(name) {
return {
name,
age,
}
}
}
// 4-1. 클래스 객체
const maker = new Foo4(20);
// -------------------------
**// 실행
console.log(typeof foo1); // object
console.log(typeof foo2); // function
console.log(typeof Foo3); // function
console.log(typeof foo3); // object
console.log(typeof Foo4); // function
console.log(typeof foo4); // object