zoukankan      html  css  js  c++  java
  • let与var的区别

    1.javascript严格模式

    在js中直接运行

    let hello="hello";
    console.log(hello)

    错误信息如下

    let hello = 'hello';
    ^^^
    
    SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
        ...

    解决方法,在文件头添加javascript严格模式声明:

    'use strict'
    let hello="hello";
    console.log(hello)

    声明后未赋值,表现相同

    'use strict';
    
    (function() {
      var varTest;
      let letTest;
      console.log(varTest); //输出undefined
      console.log(letTest); //输出undefined
    }());

    使用未声明的变量,表现不同

    (function() {
      console.log(varTest); //输出undefined(注意要注释掉下面一行才能运行)
      console.log(letTest); //直接报错:ReferenceError: letTest is not defined
    
      var varTest = 'test var OK.';
      let letTest = 'test let OK.';
    }());

    重复声明同一个变量时,表现不同

    'use strict';
    
    (function() {
      var varTest = 'test var OK.';
      let letTest = 'test let OK.';
    
      var varTest = 'varTest changed.';
      let letTest = 'letTest changed.'; //直接报错:SyntaxError: Identifier 'letTest' has already been declared
    
      console.log(varTest); //输出varTest changed.(注意要注释掉上面letTest变量的重复声明才能运行)
      console.log(letTest);
    }());

    变量作用范围,表现不同

    'use strict';
    
    (function() {
      var varTest = 'test var OK.';
      let letTest = 'test let OK.';
    
      {
        var varTest = 'varTest changed.';
        let letTest = 'letTest changed.';
      }
    
      console.log(varTest); //输出"varTest changed.",内部"{}"中声明的varTest变量覆盖外部的letTest声明
      console.log(letTest); //输出"test let OK.",内部"{}"中声明的letTest和外部的letTest不是同一个变量
    }());
  • 相关阅读:
    windows 共享文件夹 给 mac
    给mac配置adb 路径
    关于android 加载https网页的问题
    http tcp udp ip 间的关系
    手机服务器微架构设计和实现专题
    添加ssh key
    本人对于线程池的理解和实践
    使用Android Butterknife
    记一次失败的笔试(华为研发工程师-汽水瓶笔试题)
    简易坦克大战python版
  • 原文地址:https://www.cnblogs.com/samsimi/p/6773280.html
Copyright © 2011-2022 走看看