nadou
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 使用严格模式,可以检测出js中未声明的变量,可以避免全局污染
        // "use strict";
        aStr = 4;
        console.log(aStr);

        // var会出现全局污染
        // 如果重新定义了outerWidth,浏览器就不会再根据其大小而显示数值,一直为66
        var outerWidth = 66;
        console.log(window.outerWidth);

        // var声明的变量有可能发生变量提升
        function test() {
            console.log(item); // undefined
            var item = 33;
        }
        test();


        // console.log(str);
        // 报错,这是因为let、const会形成暂时性死区TDC,有效地避免了var声明造成的变量提升
        // let str = 44;    
        // const STR = 44;

        // let和const具有块作用的特点
        let name = 'ray'; 
        {
            let name = 'sunny';
            // 不允许重复定义
            // let name = 'andy';
            console.log(name);
        }
        console.log(name);
    </script>
</body>

</html>

一、var

1.1 var没有块作用域,很容易污染全局

// 函数中的变量污染了全局环境
function run() {
  web = "houlaizhe";
}
run();
console.log(web); //houlaizhe

// 没有块作用作用域时var也会污染全局
for (var i = 0; i < 10; i++) {
  console.log(i);
}
console.log(i);

1.2 块作用域

// 没有块作用时使用立即执行函数模拟块作用域
// (function() {
//   var $ = this.$ = {};
//   $.web = "后盾人";
// }.bind(window)());
// console.log($.web);

// 块作用域
{
  let $ = (window.$ = {});
  $.web = "后盾人";
}
console.log($.web);

二、let、const的相同点:

 ① 存在块作用域特性,变量只在块域中有效;

 ② 会形成暂时性死区TDC

三、let、const的区别

  • let声明变量,const主要声明常量(全部大写)

  • const只能声明一次变量,同时要赋值,且不能再次赋值,可以改变常量的引用类型值

const声明的常量不允许全新赋值举例

try {
  const URL = "https://www.baidu.com";
  URL = "https://www.taobao.com"; //产生错误
} catch (error) {
  throw new Error(error);
}

const改变常量的引用类型值

const INFO = {
  url: 'https://www.baidu.com',
  port: '8080'
};
INFO.port = '443';
console.log(INFO);

相关文章: