class의 상태(변수)처럼 보이지만, 실제로는 함수이다.
class Student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
fullName() {
return `${this.lastName} ${this.firstName}`;
}
}
const student = new Student("수지", "김");
console.log(student.firstName); // 수지
console.log(student.lastName); // 김
console.log(student.fullName()); //김 수지
❌ 함수가 아닌 프로퍼티로 쓰지 않는 이유
class Student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
<u>this.fullName = `${this.lastName} ${this.firstName}`;</u>
}
}
const student = new Student("수지", "김");
student.firstName = "안나";
console.log(student.firstName); //안나
console.log(student.lastName); // 김
console.log(student.fullName); // 김 수지
함수로 호출하는 경우, class가 생성된 이후 수정이 있어도 호출 후에 업데이트가 가능하다.
하지만, 생성자 내에 자체적으로 합치는 프로퍼티가 있다면, 이후의 수정은 변화가 없이 최초의 값만 호출될 뿐이다.
📌 더 나아가 함수호출식이 아닌 일반 속성에 접근하듯 함수를 호출하고 싶을때 필요한 키워드가 get 이다.
class Student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
**get** fullName() {
return `${this.lastName} ${this.firstName}`;
}
}
const student = new Student("수지", "김");
//console.log(student.fullName());❌
console.log(student.fullName); //김 수지
class Student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
**get** fullName() {
return `${this.lastName} ${this.firstName}`;
}
set fullName(value){
console.log(value);
}
}
const student = new Student("수지", "김");
console.log(student.fullName); //김 수지
student.fullName = '김철수'; // 김철수