객체(object)의 설계도인 클래스(class)는 서로 문법이 비슷하다.
둘의 가장 큰 차이는 constructor 라는 생성자 함수이다.
const shannon = new Employees("Shannon", ["chief","supervisor"], 29, false);
위의 코드는 new 키워드를 통해 객체를 생성했다.
즉, 아래의 두 코드는 같다. new 키워드는 객체를 생성한다.
const shannon = new Employees
const shannon = { }
이와 같이 class로 객체를 생성하는 과정을 '인스턴스화'라고 부른다.
class를 통해 생성된 객체를 인스턴스 라고 부른다.
class는 새로운 instance를 생성할 때마다 constructor( ) 메서드를 호출한다.
Employees 클래스의 생성자 함수 constructor
class Employees {
constructor(name, position, age, fulltime){
this.name = name;
this.position = position;
this.age = age;
this.fulltime = fulltime;
}
monthlyIncome(){
if(this.fulltime === true){
return 1000 * 4
}else {
return 1000 * 2.5
}
}
annualIncome(){
return this.monthlyIncome() * 12;
}
};
const shannon = new Employees("Shannon", ["chief","supervisor"], 29, false);
const mike = new Employees("Mike", ["chief","line-cook manager"], 25, true);
const ellie = new Employees("Ellie", ["server","busser"], 32, false);
const jessica = new Employees("Jessica", ["server","hall manager"], 31, true);
Employees class
의 instance
를 생성할때마다 constructor
메서드가 호출된다.constructor()
메서드는(객체 안의 함수는 메서드라고 불린다.) name, position, age, fulltime
4개의 argument(인자)
를 받는다.constructor()
메서드에 this
키워드를 사용했다. class
의 실행범위(context)에서 this
는 해당 instance
를 의미한다.constructor()
에서 인자로 넘어오는 name, position, age, fulltime
을 사용해 Employees instance의 name, position, age, fulltime
프로퍼티에 값을 할당했다.이렇게 클래스 내에서 name, position, age, fulltime
와 같이 변경 가능한 상태값이자 class내의 컨텍스트에서 어느 곳에서나 사용할 수 있는 변수를 '멤버 변수'라고 부른다.
멤버 변수는 this
키워드로 접근한다.
const shannon = new Employees("Shannon", ["chief","supervisor"], 29, false);
const mike = new Employees("Mike", ["chief","line-cook manager"], 25, true);
const ellie = new Employees("Ellie", ["server","busser"], 32, false);
const jessica = new Employees("Jessica", ["server","hall manager"], 31, true);
인스턴스는 class의 property이름과 method를 갖는 객체이다.
인스턴스 마다 모두 다른 프로퍼티 값을 갖고 있다.
인스턴스는 Class 이름에 new 를 붙여서 생성한다.
클래스 이름 우측에 괄호를 열고 닫고, 내부에는 constructor 에서 필요한 정보를 인자로 넘겨준다.
Employees
클래스의 instance를 mike
라는 변수에 저장했다.
다시 한 번! Employees
클래스의 새로운 instance를 생성하려면 new 키워드가 필요하다.
new 키워드는 constructor()
메서드를 호출하고 새로운 instance를 return 해준다.
"Mike"
라는 String, ["chief","line-cook manager"]
이라는 배열, 25
라는 Number, true
라는 Boolean을 Employees
의 constructor에 넘겨주었고, name, position, age, fulltime
프로퍼티에 각자의 값이 할당되었다.
다만 객체는 프로퍼티마다 comma(,)로 구분해줘야 했지만, 클래스는 그렇지 않다.
Employees 클래스의 메서드
monthlyIncome()
과annualIncome()
class Employees {
constructor(name, position, age, fulltime){
this.name = name;
this.position = position;
this.age = age;
this.fulltime = fulltime;
}
monthlyIncome(){
if(this.fulltime === true){
return 1000 * 4
}else {
return 1000 * 2.5
}
}
annualIncome(){
return this.monthlyIncome() * 12;
}
};
문제 :
내가 레스토랑의 직원이 되었다 생각하고 나만의 객체를 new 키워드를 통해서 생성합니다.
그리고 코드를 수정하여annualIncome
즉, 연봉 1억 4천 4백만원을 벌어봅시다!
아 참! Income은 모두 $달러 입니다. \에서 간단하게 뒤에 0 3개를 붙이면 됩니다.