function makeAgeCounter() {
let age = 20;
return {
increase: function() {
age++;
},
decrease: function() {
age--;
},
getAge: function() {
return age;
}
}
}
let ageCounter1 = makeAgeCounter();
ageCounter1.decrease();
ageCounter1.getAge(); // 19
let ageCounter2 = makeAgeCounter();
ageCounter2.increase();
ageCounter2.increase();
ageCounter2.getAge() // 22
즉시 생성자 함수가 실행되며, 변수에 클래스의 설계를 가진 새로운 객체인 인스턴스가 할당된다.
각각의 인스턴스는 클래스의 고유한 속성과 메서드를 갖게 된다.
자동차의 속성은, 브랜드, 차 이름, 색상, 현재 연료 상태, 최고 속력 등이 있다.
메서드는 "객체에 딸린 함수" => 연료 주입, 속력 설정, 운전 등이 있다.
// ES5
function Car(brand, name, color){
this.brand=brand;
this.name=name;
this.color=color;
}
Car.prototoype.drive = function{}
// ES6
class Car{
constructor(brand, name, color){
this.brand=brand;
this.name=name;
this.color=color;
}
drive(){}
}