var let const
2018-05-27 本文已影响0人
闪电西兰花
var price = 100;
price = 200;
console.log(price); //200,var声明的变量可重新赋值
var price = 300;
console.log(price); //300,var声明的变量可重复声明
function getPrice(){
var price = 100;
console.log(price);
}
getPrice(); //100,函数内部访问变量
console.log(price); //price is not defined,var声明的变量是function scope
var price = 100;
var count = 10;
if( count > 5 ){
var discount = price * 0.6;
}
console.log(discount); //60,没有function,discount是全局变量
var price = 100;
var count = 10;
if( count > 5 ){
let discount = price * 0.6;
}
console.log(discount); //discount is not defined,let和const是block scope,这里使用const也是相同结果
let count = 10;
count = 20;
console.log(count); //20,let声明的变量可重新赋值
let count = 20; //Identifier 'count' has already been declared,let声明的变量不可以重复声明
let discount = 0.9; //全局作用域下的变量
if( count > 5 ){
let discount = 0.5; //block中的变量
}
console.log(discount); //0.9,获取全局变量
const key = '123';
key = '1234'; //Assignment to constant variable,const声明的变量不可重新赋值
const person = {
name: 'Asher',
age: 5
}
person = {
name: 'allen',
age: 2
}
cosnole.log(person); //Assignment to constant variable,指针指向新的地方了,不可以
const person = {
name: 'Asher',
age: 5
}
person.age = 6;
console.log(person); //{name: "Asher", age: 6},const晟敏的对象可以修改属性
//let使用场景
for(var i=0;i<5;i++){
console.log(i);
setTimeout(function(){
console.log(i); //输出5个5
},1000)
}
for(let i=0;i<5;i++){
console.log(i);
setTimeout(function(){
console.log(i); //输出01234
},100)
}
console.log(color);
var color = 'blue'; //undefined,变量提升
//ES6中建议使用var/let/const的规则
//默认使用const
//当变量需要重新绑定或更新时使用let
//尽量不使用var
console.log(color);
let color = 'blue'; //color is not defined,暂时性死区,let声明不会被提升到当前执行上下文的顶部,const也同样