likes
comments
collection
share

[JS基础强化] var let const 你分得出区别吗?

作者站长头像
站长
· 阅读数 45

js基础强化

本章内容:

本章内容 对var let const 的使用进行详解,针对这些声明方式进行了对比并总结出了详细使用规则。有经验的同学可以直接看结果不看demo。

基本用法

1.直接定义

   let name;
   var age;
   const address;
   console.log(name,age,address) //undefined undefined undefined

2.连续定义

与上面相同只不过是一个简化的写法

   let name,age,address;
   console.log(name,age,address)// undefined undefined undefined

3.连续定义并赋值

   let name='anlijun',age='22',address='南京市';
   console.log(name,age,address)// 'anlijun' 22 '南京市'

var的探究

1. 变量提升问题

    console.log(author); //undefined
    var author='anlijun';
    
解释: 在js的解析器去解析的时候 会有有限将变量的var 的声明提到前面去,
因此上面的操作在实际运行的时候就变成了下面这样。(ps 除了变量提升还有函数提升,下次讲解)

     var author
     console.log(author); //undefined
     author='anlijun'

2. 变量作用域问题

    if(true){
        var author='anlijun';
    }
    console.log(author);//anlijun
    
   (()=>{
       var address="南京市"
   })()
       console.log(address)//报错 address is not defined
解释:
    这里我定义了两个变量 author 在if语句的代码块中,address 在匿名箭头函数中;
    由于var 定义的变量只有函数作用域(只能在函数内部访问)没有块级作用域(if for 等等等的代码块都会失效,其实都相当于定义在了全局)所以在外面能访问到 author
      

3. 变量的重复声明问题

    var author="我不是药神";
    var author="anlijun";
    console.log(author)//"anlijun"
    
    重复声明不会报错,而是后面的值覆盖前面的值

4. 变量的全局声明问题

    var author="anlijun";
    (()=>{
        var address="南京市"
    })();
    if(true){
       var day="20230608"
    }
    console.log(window.author,window.address,day);//anlijun undefined 20230608
    结论 在使用var时只要不是定义在函数中那么这个变量就会成为globalThis的属性。

let 的探究

1. 变量提升问题

    console.log(author); // Cannot access 'author' before initialization; 
    报错 初始化前无法访问author
    let author='anlijun';

2. 变量作用域问题

   if(true){
        let author='anlijun';
    }
    console.log(author);//author is not defined
    
   (()=>{
       let address="南京市"
   })()
       console.log(address)//代码终止了
 
  正常两个都是xxxis not defined 由于报错下面代码不会被执行了

3. 变量的重复声明问题

    let author="我不是药神";
    let author="anlijun";
    console.log(author)// Identifier 'author' has already been declared 
    author 变量早就被创建了
    同理
    var address="北京";
    let address="南京"
    这个也会报错

4. 变量的全局声明问题

   let author="anlijun";
   console.log(window.author)//undefined

const的探究

const 的demo 就不按照上面敲了 他跟let是一样的唯独有一点区别我来演示一下

1. const 的不可修改问题

    const author="anlijun";
    author ="666"; //报错 Assignment to constant variable.
    不能对常量进行修改;
    
    const person ={
        name:'anlijun',
        address:'南京'
    }
    person.address="北京";
    //这样可以改因为内存地址没有改

结论

在实际开发中应该在变量是不会更改的情况使用const,其余情况使用let不使用var。

下图中对var let const 进行了对比,绿色是优点,黄绿色是正常,红色是缺点。 [JS基础强化] var let const 你分得出区别吗?

转载自:https://juejin.cn/post/7242129949180362812
评论
请登录