자바스크립트 엔진은 프로퍼티를 생성할 때 프로퍼티의 상태를 나타내는 프로퍼티 어트리뷰트를 기본값으로 자동 정의한다.
데이터 프로퍼티
: 키와 값으로 구성된 일반적인 프로퍼티
프로퍼티 어트리뷰트 : 자바스크립트 엔진이 관리하는 내부 상태 값
- Value : 프로퍼티의 값
- Writable : 프로퍼티의 값의 변경 여부, 기본값 true
- Enumerable : 프로퍼티의 열거 가능 여부 , 기본값 true
- Configurable : 프로퍼티의 재정의 가능 여 , 기본값 true
const person = {
name: "kiwon"
};
//첫번째 인자에는 참조값, 두번째 인자에는 프로퍼티 키값
// 반환값으로 디스크립터 객체를 반환한다.
console.log(Object.getOwnPropertyDescriptor(person, "name"));
접근자 프로퍼티
: 자체적으로 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성
프로퍼티 어트리뷰트
- Get : 데이터 프로퍼티의 값을 읽을 때 호출되는 접근자 함수, getter 함수가 호출되고 그 결과가 프로퍼티 값으로 반환된다.
- Set : 접근자 프로퍼티를 통해 데이터 프로퍼티의 값을 저장할 때 호출되는 접근자 함수, setter함수가 호출되고 그 결과가 프로퍼티 값으로 저장된다.
- Enumerable : 동일
- Configurable : 동일
const person2 = {
//데이터 프로퍼티
firstName: "hello",
lastName: "world",
//getter
get fullName(){
return this.firstName +" "+ this.lastName;
},
//setter
set fullName(name){
[this.firstName, this.lastName] = name.split(" ");
}
};
// 데이터 프로퍼티로 접근
console.log(person2.firstName + " " + person2.lastName);
// 접근자 프로퍼티로 접근ㄴ
// 자동적으로 setter함수 호출
person2.fullName = "wow javascript";
console.log(person2);
// 자동적으로 getter함수 호출
console.log(person2.fullName);
let des = Object.getOwnPropertyDescriptor(person2, "firstName");
// 데이터 프로퍼티 조회
console.log(des)
des = Object.getOwnPropertyDescriptor(person2, "fullName");
// 접근자 프로퍼티 조회
console.log(des);
'WEB > JS' 카테고리의 다른 글
[JS] constructor, non-constructor (0) | 2023.11.28 |
---|---|
[JS] 생성자 함수에 의한 객체 생성 (0) | 2023.11.28 |
[JS] let, const키워드와 블록 레벨 스코프 (1) | 2023.11.27 |
[JS] scope(유효범위) (0) | 2023.11.25 |
[JS] recursive // callback (2) | 2023.11.25 |