JS 块作用域

变量声明

varletconst

作用域:变量的作用范围

  • 全局 - 非函数
  • 函数 - 函数包含
  • 块作用域 -一对{}包含的范围

var

  • 支持变量声明预解析
  • 不支持块作用域
  • 允许重复声明

let

  • 不支持变量声明预解析(先声明后使用)
  • 支持块作用域
  • 不允许重复声明(暂存死区)

const

  • 不支持变量声明预解析(先声明后使用)
  • 支持块作用域
  • 不允许重复声明(暂存死区)
  • 常量(值一旦确定,不允许修改,所以必须初始化)

例子:

{
    var a = 1;
    let b = 2;
    const c = 3;
}

console.log(a);
console.log(b);
console.log(c);

结果为:

1
Uncaught ReferenceError: b is not defined
Uncaught ReferenceError: c is not defined

故let和const在块作用域外是无法引用的

html的例子:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        button.active {
            background: yellow;
        }

        p {
            display: none;
        }

        p.active {
            display: block;
        }
    </style>
</head>

<body>
    <button class="active">选项一</button>
    <button>选项二</button>
    <button>选项三</button>
    <p>内容一</p>
    <p>内容二</p>
    <P>内容三</P>
</body>
<script>
    var buttons = document.querySelectorAll('button');
    var ps = document.querySelectorAll('p');

    for (let i = 0; i < buttons.length; i++) {
        buttons[i].onclick = function () {
            for (let i = 0; i < buttons.length; i++) {
                buttons[i].className = '';
                ps[i].className = '';
            }

            this.className = 'active';
            ps[i].className = 'active';
        }
    }
</script>

</html>

效果:
效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值