키워드 'const'는 값을 변경 불가능하게 만들지 않습니다. 무슨 뜻인가요?
있다 CONST 정의 에 ES6 탐색 박사 악셀 Rauschmayer으로는 :
const
let처럼 작동하지만 선언 한 변수는 나중에 변경할 수없는 값 으로 즉시 초기화되어야합니다 . […]const bar = 123; bar = 456; // TypeError: `bar` is read-only
그리고 그는 쓴다
const
변수가 항상 같은 값을 가짐을 의미 할뿐 값 자체가 변하지 않거나 불변이된다는 의미는 아닙니다.
나는이 함정에 약간 혼란스러워한다. 누구 const
든지이 함정을 명확하게 정의 할 수 있습니까 ?
MDN은 그것을 멋지게 요약합니다.
const 선언은 값에 대한 읽기 전용 참조를 만듭니다. 보유한 값이 변경 불가능하다는 의미가 아니라 변수 식별자를 재 할당 할 수 없다는 의미입니다. 예를 들어 콘텐츠가 객체 인 경우 이는 객체 자체가 여전히 변경 될 수 있음을 의미합니다.
더 간결하게 : const는 불변의 바인딩을 만듭니다.
즉, var와 마찬가지로 const는 무언가를 저장하는 가변 메모리 청크를 제공합니다. 그러나 const는 동일한 메모리 청크를 계속 참조해야한다고 지시합니다. 변수 참조가 일정하기 때문에 변수를 다른 메모리 청크에 다시 할당 할 수 없습니다.
선언 한 후에 무언가를 일정하고 변하지 않게 만들려면 Object.freeze()
. 그러나 이는 얕고 키 / 값 쌍에서만 작동합니다. 전체 개체를 고정하려면 약간 더 많은 노력이 필요합니다. 이를 수행하는 방식으로 반복하는 것은 훨씬 더 어렵습니다. 정말로 필요하다면 Immutable.js 와 같은 것을 확인하는 것이 좋습니다.
const
JavaScript로 무언가를 만들 때 다른 것을 참조하도록 변수 자체를 재 할당 할 수 없습니다. 그러나 변수는 여전히 변경 가능한 객체를 참조 할 수 있습니다.
const x = {a: 123};
// This is not allowed. This would reassign `x` itself to refer to a
// different object.
x = {b: 456};
// This, however, is allowed. This would mutate the object `x` refers to,
// but `x` itself hasn't been reassigned to refer to something else.
x.a = 456;
문자열 및 숫자와 같은 기본 요소의 경우 const
값을 변경하지 않고 대신 새 값을 변수에 할당하기 때문에 이해하기가 더 쉽습니다.
리 바인딩
const
및 let
선언 식별자와 값 사이 (일명 재 할당) rebindings 허용할지 여부를 제어 :
const x = "initial value";
let y = "initial value";
// rebinding/reassignment
try { x = "reassignment" } catch(e) { console.log(x) } // fails
y = "reassignment"; // succeeds
console.log(y);
불변성
불변성은 유형 수준에서 제어됩니다. Object
는 변경 가능한 유형 인 반면 String
은 변경 불가능한 유형입니다.
const o = {mutable: true};
const x = "immutable";
// mutations
o.foo = true; // succeeds
x[0] = "I"; // fails
console.log(o); // {mutable: true, foo: true}
console.log(x); // immutable
const는 처음 할당 된 값을 변경할 수 없음을 의미합니다.
먼저 js 의 값 이 무엇인지 정의하십시오 . 값은 부울, 문자열, 숫자, 개체, 함수 및 정의되지 않은 값이 될 수 있습니다.
좋아요 : 사람들이 당신의 이름으로 당신을 부릅니다. 그것은 변하지 않습니다. 그러나 옷을 갈아 입습니다. 사람들과 당신 사이 의 결속 은 당신의 이름입니다. 나머지는 바뀔 수 있습니다. 이상한 예를 들어 죄송합니다.
그래서 몇 가지 예를 들어 보겠습니다.
// boolean
const isItOn = true;
isItOn = false; // error
// number
const counter = 0;
counter++; // error
// string
const name = 'edison';
name = 'tesla'; // error
// objects
const fullname = {
name: 'albert',
lastname: 'einstein'
};
fullname = { // error
name: 'werner',
lastname: 'heisenberg'
};
// NOW LOOK AT THIS:
//
// works because, you didn't change the "value" of fullname
// you changed the value inside of it!
fullname.name = 'hermann';
const increase = aNumber => ++aNumber;
increase = aNumber => aNumber + 1; // error
// NOW LOOK AT THIS:
//
// no error because now you're not changing the value
// which is the decrease function itself. function is a
// value too.
let anotherNumber = 3;
const decrease = () => --anotherNumber;
anotherNumber = 10; // no error
decrease(); // outputs 9
const chaos = undefined;
chaos = 'let there be light' // error
const weird = NaN;
weird = 0 // error
As you can see, unless you're not changing the "first" assigned value to a const, no error. Whenever you try to change the first assigned value to something else, it gets angry, and it gives an error.
So, this is the second thing you might know when using const
. Which is, it should be initialized to a value on its declaration or it will be angry.
const orphan; // error
const rich = 0; // no error
ES6
/ES2015
const
keyword:
The const
keyword is used to declare a block scoped variable (like declaring with let
). The difference between declaring a variable with const
and let
is the following:
- A variable declared
const
cannot be reassigned. - A variable declared with
const
has to be assigned when declared. This is a logical consequence of the previous point because a variable declared withconst
cannot be reassigned, that's why we have to assign it exactly once when we declare the variable.
Example:
// we declare variable myVariable
let myVariable;
// first assignment
myVariable = 'First assingment';
// additional assignment
myVariable = 'Second assignment';
// we have to declare AND initialize the variable at the same time
const myConstant = 3.14;
// This will throw an error
myConstant = 12;
In the above example we can observe the following:
- The variable
myVariable
declared withlet
can first be declared and then be assigned. - The variable
myConstant
declared withconst
has to be declared and assigned at the same time. - When we try to reassign the variable
myConstant
we get the following error:
Uncaught TypeError: Assignment to constant variable
Caveat: The variable assigned with const
is still mutable:
A variable declared with const
just can't be reassigned, it is still mutable. Being mutable means that the data structure (object, array, map, etc) which was assigned to the const
variable still can be altered (i.e. mutated). Examples of mutation are:
- Adding/deleting/altering a property of an object
- Changing the value of an array at a specific array index
If really want an object to be not mutable you will have to use something like Object.freeze()
. This is a method which freezes an object. A frozen object can no longer be changed and no new properties can be added.
Example:
const obj = {prop1: 1};
obj.prop1 = 2;
obj.prop2 = 2;
console.log(obj);
// We freeze the object here
Object.freeze(obj);
obj.prop1 = 5;
delete obj.prop2;
// The object was frozen and thus not mutated
console.log(obj);
'developer tip' 카테고리의 다른 글
TCP 옵션 SO_LINGER (영)-필요한 경우 (0) | 2020.09.20 |
---|---|
고정 너비 텍스트 파일 읽기 (0) | 2020.09.20 |
WPF Textblock, Text 속성의 줄 바꿈 (0) | 2020.09.20 |
날짜 문자열 또는 개체의 NSArray 정렬 (0) | 2020.09.20 |
Gradle 인수에 대한 compile () 메서드를 찾을 수 없습니다. (0) | 2020.09.20 |