Object.freeze() vs const

前端 未结 5 468
感情败类
感情败类 2020-12-12 10:27

Object.freeze() seems like a transitional convenience method to move towards using const in ES6.

Are there cases where both take their place in the cod

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 10:49

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

    The above example it completely makes your object immutable.

    Lets look following example.

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

    It won't give any error.

    But If you try like that

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

    It will throw an error like that "obj is read-only".

    Another use case

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

    It will throw 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.

提交回复
热议问题