JS中使用const声明变量&&使用Object.freeze冻结对象
作者:互联网
const
Some developers prefer to assign all their variables using const
by default, unless they know they will need to reassign the value. Only in that case, they use let
.
一些开发人员更喜欢在默认情况下使用const分配所有变量,除非他们知道需要重新分配值。只有在这种情况下,他们才使用let。
it is important to understand that objects (including arrays and functions) assigned to a variable using const are still mutable. Using the const declaration only prevents reassignment of the variable identifier.
重要的是要理解,使用const分配给变量的对象(包括数组和函数)仍然是可变的。使用const声明只能防止变量标识符(即变量名)的重新分配。
const s = [5, 6, 7]; //s = [1, 2, 3];//没注释掉此句就会报错:TypeError: "s" is read-only s[2] = 45; console.log(s);//上上面那句注释掉之后,控制台输出:[ 5, 6, 45 ]
As you can see, you can mutate the object [5, 6, 7] itself and the variable s will still point to the altered array [5, 6, 45]. Like all arrays, the array elements in s are mutable, but because const was used, you cannot use the variable identifier s to point to a different array using the assignment operator.
如您所见,您可以对对象[5,6,7]本身进行变异,变量s仍将指向更改后的数组[5,6,45]。与所有数组一样,s中的数组元素是可变的,但由于使用了const,不能用赋值运算符使变量标识符s指向其他数组。
Object.freeze()
若要使对象(包括数组和函数)里的元素也不能改变,则要用到Object.freeze。
Any attempt at changing the object will be rejected, with an error thrown if the script is running in strict mode.our editor runs in strict mode by default.you are going to use Object.freeze
to prevent object from changing,so that no one is able to alter the value of the object, add, or delete properties.
任何更改对象的尝试都将被拒绝,如果脚本在严格模式下运行,将抛出错误。默认情况下,我们的编辑器以严格模式运行。您将使用Object.freeze以防止对象更改,以便任何人都无法更改对象的值、添加或删除属性。
function freezeObj() { const MATH_CONSTANTS = { PI: 3.14 }; Object.freeze(MATH_CONSTANTS);//冻结对象,使其无法被更改。 try { MATH_CONSTANTS.PI = 99;//因为Object.freeze了,所以无法更改!!! } catch(ex) { console.log(ex);//控制台抛出错误:[TypeError: Cannot assign to read only property 'PI' of object '#<Object>'] } return MATH_CONSTANTS.PI; } //测试: const PI = freezeObj(); console.log(PI); //3.14 若上面没有加Object.freeze(MATH_CONSTANTS),则为99。
标签:object,const,JS,Object,freeze,PI,CONSTANTS 来源: https://www.cnblogs.com/168-h/p/16686492.html