ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

JS中使用const声明变量&&使用Object.freeze冻结对象

2022-09-12 16:31:26  阅读:190  来源: 互联网

标签:object const JS Object freeze PI CONSTANTS


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有