标签:define 作用域 方法 var reference efi declared 复合 float
参考资料:
http://es6.ruanyifeng.com/#docs/let
测试环境(本文的代码均是在chrome下运行)
在<script>标签中添加‘use strict‘,即严格模式
let
let a = 1; let a = 2; //Uncaught SyntaxError: Identifier ‘a‘ has already been declared let b = 1; b = 2; console.log(b); //2
console.log(a); //Uncaught ReferenceError: a is not defined let a = 1;
{
let a = 1;
console.log(a); //1
}
console.log(a);// Uncaught ReferenceError: a is not defined
const
//一旦声明,值不能更改
const a = 1;
console.log(a); //1
a = 2;
console.log(a); //Uncaught TypeError: Assignment to constant variable.
//只声明不赋值
const b; //Uncaught SyntaxError: Missing initializer in const declaration
//不能重复声明
const b = 1;
const b = 2; //Uncaught SyntaxError: Identifier ‘b‘ has already been declared
//值为对象时,对象的属性/属性值可以更改
const b = {
num : 1
}
b.num = 2;
console.log(b.num); //2
没有变量提升
console.log(a); //Uncaught ReferenceError: a is not defined const a = 1;
{
const a = 1;
console.log(a); //1
}
console.log(a); //Uncaught ReferenceError: a is not defined
总结
const和let命令都是es6在es5声明变量方法(var function)基础上添加的新方法:
共同点:
不同点:
const声明的变量是只读变量,变量声明之后值不允许更改,原因是const声明的变量指向是一个内存地址,对于简单数据类型(number,boolean,string),值就保存在变量指向的那个内存地址,因此等同于常量。但对于复合类型的数据(主要是对象和数组),变量指向的内存地址,保存的只是一个指针,const只能保证这个指针是固定的,至于它指向的数据结构是不是可变的,就完全不能控制了。

标签:define 作用域 方法 var reference efi declared 复合 float
原文地址:http://www.cnblogs.com/sanxiaoshan/p/6846373.html