[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 답변

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)