[javascript] read-only 속성
조회수 1197회
mdn 문서를 보면 property중에 read-only 라고 적혀있는 것들이 있는데요. read-only와 const 의 차이가 무엇인가요?
제가 mdn을 읽어보니
아래 글은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const 의 일부인데요.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
read-only라면 객체의 key 에 따른 value값을 변경하지 못하는데, const 로 선언한 객체는 value를 바꿀 수 있다고 생각하면 될까요?
// const also works on objects
const MY_OBJECT = {'key': 'value'};
// Attempting to overwrite the object throws an error - Uncaught TypeError: Assignment to constant variable.
MY_OBJECT = {'OTHER_KEY': 'value'};
// However, object keys are not protected,
// so the following statement is executed without problem
MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable
// The same applies to arrays
const MY_ARRAY = [];
// It's possible to push items into the array
MY_ARRAY.push('A'); // ["A"]
// However, assigning a new array to the variable throws an error - Uncaught TypeError: Assignment to constant variable.
MY_ARRAY = ['B'];
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
const
로 선언한 변수는 해당 변수에 다른 객체를 재할당을 할 수 없다는 의미입니다.객체 자체의 속성값 접근과 관련된 설정은 Object.defineProperties 라는 메소드로 따로 지정할 수 있으며 read-only 속성값도 만들 수 있습니다. https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties
댓글 입력