()를 써서 호출하는 것이 아니라, 일반 프로퍼티처럼 사용한다)class에서도 사용할 수 있다.접근자 프로퍼티에는 getter와 setter 두가지가 있는데, 각각 get 키워드와 set 키워드를 사용해 정의할 수 있다.
let obj = {
get propName() {
// getter, obj.propName을 실행할 때 실행되는 코드
},
set propName(value) {
// setter, obj.propName = value를 실행할 때 실행되는 코드
}
};
()없이, 일반 프로퍼티처럼 사용한다. (위 주석에 나와 있는 것처럼)thislet user = {
name: "John",
surname: "Smith",
get fullName() {
return `${this.name} ${this.surname}`;
},
set fullName(value) {
[this.name, this.surname] = value.split(" ");
}
};
// 주어진 값을 사용해 set fullName이 실행됩니다.
user.fullName = "Alice Cooper";
alert(user.name); // Alice
alert(user.surname); // Cooper
이렇게 getter와 setter 메서드를 구현하면 객체엔 fullName이라는 '가상’의 프로퍼티가 생긴다. 가상의 프로퍼티는 읽고 쓸 순 있지만 실제로는 존재하지는 않는다.

user를 입력해보면 위와 같이 내부에 fullName 프로퍼티가 존재하지 않는 것을 확인할 수 있다. 그럼에도 user.fullName을 하면 값을 읽을 수 있다.이 예시는 https://ko.javascript.info/prototype-inheritance#ref-1393 여기에서 내가 따로 가져옴.
let user = {
name: "John",
surname: "Smith",
set fullName(value) {
**[this.name, this.surname] = value.split(" ");**
},
get fullName() {
return `${this.name} ${this.surname}`;
}
};
let admin = {
__proto__: user,
isAdmin: true
};
alert(admin.fullName); // John Smith (*)
// setter 함수가 실행됩니다!
admin.fullName = "Alice Cooper"; // (**)
alert(admin.fullName); // Alice Cooper, setter에 의해 추가된 admin의 프로퍼티(name, surname)에서 값을 가져옴
alert(user.fullName); // John Smith, 본래 user에 있었던 프로퍼티 값
split()메소드와 destructuring 사용해서 this.name과 this.surname setter 구현한 부분 신기하군name, surname)를 생성했다고 볼 수 있다.
admin 객체에 name과 surname 프로퍼티를 setter를 통해 새로 생성했기 때문에, admin.fullName으로 접근 시 이전과는 다르게 프로토타입에 정의된 name과 surname이 아닌 admin에 정의된 name과 surname을 참조하게 된다.
class ClassWithGetSet {
#msg = "hello world";
get msg() {
return this.#msg;
}
set msg(x) {
this.#msg = `hello ${x}`;
}
}
const instance = new ClassWithGetSet();
console.log(instance.msg); // "hello world"
instance.msg = "cake";
console.log(instance.msg); // "hello cake"
prototype property of the class and are thus shared by all instances of the class.