es64 const
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>const命令</title> <script src="../../../vendor/traceur.js"></script> <script src="../../../vendor/bootstrap.js"></script> <script type="text/traceur"> const Pi = 3.1415926535;//只能赋一次值 console.log(Pi); Pi = 3; // Pi is read-only -- Error console.log(Pi); const Pi = 3.1415926535; console.log(Pi); //3.1415926535 console.log(5 * Pi);//15.7079632675 if (true) { const Pi = 3.14159265; }; console.log(Pi); //Pi is not defined var Pi = 88; if (true) { console.log(Pi); //undefined const Pi = 3.14159265; console.log(s); }; </script> </head> <body> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>const不可重复声明</title> <script src="../../../vendor/traceur.js"></script> <script src="../../../vendor/bootstrap.js"></script> <script type="text/traceur"> { var a = 100; const a = 200; console.log(a);//报错,局部不可重复声明 } const person = {};//person是地址 person.name = "Zhangsan"; person.age = 30; console.log(person.name); //Zhangsan console.log(person.age); //30 console.log(person); //Object {name: "Zhangsan", age: 30} person = {}; //person is read-only </script> </head> <body> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>const数组</title> <script src="../../../vendor/traceur.js"></script> <script src="../../../vendor/bootstrap.js"></script> <script type="text/traceur"> const arr = []; console.log(arr);//[] console.log(arr.length);//0 console.log("------"); arr.push("Hello world!"); console.log(arr);//["Hello world!"] console.log(arr.length);//1 console.log("------"); arr.length = 0;//清空数组 console.log(arr);//[] console.log(arr.length); console.log("------"); // 错误用法 arr = ["Hello Everyone!"]; const person = Object.freeze({kk:'kk'});//const对象冻结,对象里面的属性都不能改变 person.name = "Zhangsan"; person.age = 30; console.log(person.kk); //kk console.log(person.name); //undefined console.log(person.age); //undefined console.log(person); //Object {kk: "kk"} const person = Object.freeze({//属性只读 name: "Zhangsan", age : 30 }); console.log(person.name); //Zhangsan console.log(person.age); //30 console.log(person); //Object //冻结函数 var constantize = (obj) => { Object.freeze(obj); Object.keys(obj).forEach( (key, value) => { if ( typeof obj[key] === 'object' ) { constantize( obj[key] );//key也冻结 }; }); }; </script> </head> <body> </body> </html>