program tip

Object.freeze () 대 const

radiobox 2020. 8. 3. 08:34
반응형

Object.freeze () 대 const


Object.freeze()constES6에서 사용하기 위해 전환하는 편리한 방법처럼 보입니다 .

코드에서 둘 다 발생하는 경우가 있거나 불변 데이터로 작업하는 선호되는 방법이 있습니까?

Object.freeze()지원하는 모든 브라우저를 사용할 때까지 사용해야 const하고 const대신 사용으로 전환해야 합니까?


constObject.freeze완전히 다른 두 가지 있습니다.

const바인딩에 적용됩니다 ( "변수"). 변경 불가능한 바인딩을 만듭니다. 즉, 바인딩에 새 값을 할당 할 수 없습니다.

Object.freeze ,보다 구체적으로 객체 값 에서 작동 합니다 . 객체를 불변으로 만듭니다. 즉, 속성을 변경할 수 없습니다.


ES5 Object.freeze에서는 프리미티브에서 작동하지 않으며 아마도 const객체보다 더 일반적으로 선언 됩니다. ES6에서 프리미티브를 고정 할 수 있지만을 지원합니다 const.

반면에 const객체를 선언하는 데 사용되는 것은 "동결"되지 않으며 전체 객체를 다시 선언 할 수는 없지만 키를 자유롭게 수정할 수 있습니다. 반면에 고정 된 개체를 다시 선언 할 수 있습니다.

Object.freeze 또한 얕으므로 중첩 된 객체에 재귀 적으로 적용하여 보호해야합니다.

var ob1 = {
   foo : 1,
    bar : {
        value : 2   
    }
};
Object.freeze( ob1 );

const ob2 = {
   foo : 1,
    bar : {
        value : 2   
    }
}

ob1.foo = 4;  // (frozen) ob1.foo not modified
ob2.foo = 4;  // (const) ob2.foo modified

ob1.bar.value = 4;  // (frozen) modified, because ob1.bar is nested
ob2.bar.value = 4;  // (const) modified

ob1.bar = 4;  // (frozen) not modified, bar is a key of obj1
ob2.bar = 4;  // (const) modified

ob1 = {};  // (frozen) ob1 redeclared
ob2 = {}; // (const) ob2 not redeclared

var obj = {
  a: 1,
  b: 2
};
Object.freeze(obj);
obj.newField = 3; // You can't assign new field , or change current fields

위의 예제는 객체를 불변으로 만듭니다.

다음 예제를 보자.

const obj = {
  a: 1,
  b: 2
};
obj.a = 13; // You can change a field
obj.newField = 3; // You can assign new field.

오류가 발생하지 않습니다.

하지만 그렇게하면

const obj = {
      a: 1,
      b: 2
    };
obj = {
 t:4
};

"obj is read-only"와 같은 오류가 발생합니다.

다른 사용 사례

const obj = {a:1};
var obj = 3;

던질 것이다 Duplicate declaration "obj"

Also according to mozilla docs const explanation

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, solely that the variable identifier can not be reassigned.

This examples created according to babeljs ES6 features.


Summary:

const and Object.freeze() serve totally different purposes.

  • const is there for declaring a variable which has to assinged right away and can't be reassigned. variables declared by const are block scoped and not function scoped like variables declared with var
  • Object.freeze() is a method which accepts an object and returns the same object. Now the object cannot have any of its properties removed or any new properties added.

Examples const:

Example 1: Can't reassign const

const foo = 5;

foo = 6;

The following code throws an error because we are trying to reassign the variable foo who was declared with the const keyword, we can't reassign it.

Example 2: Data structures which are assigned to const can be mutated

const object = {
  prop1: 1,
  prop2: 2 
}

object.prop1 = 5;   // object is still mutable!
object.prop3 = 3;   // object is still mutable!

console.log(object);  // object is mutated

In this example we declare a variable using the const keyword and assign an object to it. Although we can't reassign to this variable called object, we can mutate the object itself. If we change existing properties or add new properties this will this have effect. To disable any changes to the object we need Object.freeze().

Examples Object.freeze():

Example 1: Can't mutate a frozen object

object1 = {
  prop1: 1,
  prop2: 2
}

object2 = Object.freeze(object1);

console.log(object1 === object2); // both objects are refer to the same instance

object2.prop3 = 3; // no new property can be added, won't work

delete object2.prop1; // no property can be deleted, won't work

console.log(object2); // object unchanged

In this example when we call Object.freeze() and give object1 as an argument the function returns the object which is now 'frozen'. If we compare the reference of the new object to the old object using the === operator we can observe that they refer to the same object. Also when we try to add or remove any properties we can see that this does not have any effect (will throw error in strict mode).

Example 2: Objects with references aren't fully frozen

const object = {
  prop1: 1,
  nestedObj: {
    nestedProp1: 1,
    nestedProp2: 2,
  } 
}


const frozen = Object.freeze(object);

frozen.prop1 = 5; // won't have any effect
frozen.nestedObj.nestedProp1 = 5; //will update because the nestedObject isn't frozen

console.log(frozen);

This example shows that the properties of nested objects (and other by reference data structures) are still mutable. So Object.freeze() doesn't fully 'freeze' the object when it has properties which are references (to e.g. Arrays, Objects).


Let be simple.

They are different. Check the comments on the code, that will explain each case.

Const - It is block scope variable like let, which value can not reassignment, re-declared .

That means

{
 const val = 10;  // you can not access it outside this block, block scope variable

}

console.log(val); // undefined because it is block scope 

const constvalue = 1;
constvalue = 2; // will give error as we are re-assigning the value;
const obj = { a:1 , b:2};

obj.a = 3;
obj.c = 4;
console.log(obj); // obj = {a:3,b:2,c:4} we are not assigning the value of identifier we can 
                  // change the object properties, const applied only on value, not with properties
obj = {x:1};     // error you are re-assigning the value of constant obj 
obj.a = 2 ;     // you can add, delete element of object

The whole understanding is that const is block scope and its value is not re-assigned.

Object.freeze: The object root properties are unchangeable, also we can not add and delete more properties but we can reassign the whole object again.

var x = Object.freeze({data:1,
    name:{
    firstname:"hero", lastname:"nolast"
    }
});

x.data = 12;  // the object properties can not be change but in const you can do
x.firstname ="adasd"; // you can not add new properties to object but in const you can do

x.name.firstname = "dashdjkha"; // The nested value are changeable 

//The thing you can do in Object.freeze but not in const

x = { a: 1};  // you can reassign the object when it is Object.freeze but const its not allowed

// One thing that is similar in both is, nested object are changeable

const obj1 = {nested :{a:10}};
var obj2 =  Object.freeze({nested :{a:10}});

obj1.nested.a = 20; // both statement works
obj2.nested.a = 20;

Thanks.

참고URL : https://stackoverflow.com/questions/33124058/object-freeze-vs-const

반응형