【ECMAScript6标准入门】2.const的使用
来源:互联网 发布:用户mac地址绑定错误 编辑:程序博客网 时间:2024/06/12 19:42
//2.3.1const用于声明一个常量,不量声明,常量的值不能改变。const PI = 3.1415926;//声明的同时就必须给予赋值//PI = 0;//报错,TypeError: Assignment to constant variable.console.log(PI);//作用域与let相同{const a = "123";}//console.log(a);//报错,ReferenceError: a is not definedvar message = "Hello";let age = 15;//以下两行都会报错 //const message = "world";//报错,SyntaxError: Identifier 'message' has already been declared//const age = 10;//报错,Duplicate declaration "age//2.3.2本质//const实际上保证的并不是变量的值不得改动,而是变量指向的那个内存地址不得改动。const foo = {}foo.prop = 123;foo.prop = 432;console.log(foo);//{ prop: 432 }const arr = [];arr.push("hello");//可执行arr.length = 0;//可执行//arr = ["adf"];//报错,TypeError: Assignment to constant variable.console.log(arr);const foo2 = Object.freeze({})//将对象冻结foo2.prop = 123;console.log(foo2);//{}const arr2 = Object.freeze([]);//arr2.push("hello");//报错,TypeError: Can't add property 0, object is not extensibleconsole.log(arr2);//[]//将对象彻底冻结函数var constantize = (obj) => {Object.freeze(obj);Object.keys(obj).forEach((key,i) => {if (typeof obj[key] === 'object') {constantize(obj[key]);}});};
运行结果:
整理内容摘自《ES6标准入门》第三版 阮一峰
阅读全文
0 0
- 【ECMAScript6标准入门】2.const的使用
- 【ECMAScript6标准入门】1.let的使用
- ECMAScript6标准Promise的使用
- ECMAScript6标准Class的使用
- 【ECMAScript6标准入门】String
- ECMAScript6标准Set和Map的使用
- ECMAScript6标准Symbol类型的使用
- ECMAScript6标准SIMD使用
- 【ECMAScript6标准入门】3.变量的解析赋值
- ECMAscript6快速入门-let和const
- ECMAScript6标准数组的扩展
- 【ECMAScript6标准入门】Babel之HelloWorld
- ECMAScript6的使用心得
- ECMAScript6入门
- ECMAscript6快速入门-函数的扩展
- ECMAScript6标准Module
- ECMAScript6(ES6)标准之let、const关键字与块级作用域
- ECMAScript6中Generator和yield的使用
- linux进程间通信之共享内存
- 考察的是js的预解析
- Ecliose导文件
- handsontable日期控件汉化
- unity3d相关文档整理
- 【ECMAScript6标准入门】2.const的使用
- Lua之Sprite使用
- gem install redis报错解决办法
- Shiro报错No SecurityManager accessible to the calling code
- Linux 的各种 signal
- mysql数据库备份和还原
- ubuntu下如何把用户的语言环境变量改为中文
- 用conda创建python虚拟环境
- c语言运算符优先级,结合性(左/右结合详解)