js闭包及var和let对闭包的作用

js闭包及var和let对闭包的作用

为了便于理解,本文用一个例子程序来体现js闭包和var、let变量声明对所谓闭包的作用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script>
    function test() {
        for(var i=0;i<10;i++){
            console.log(i);
        }
    };

    var testclosing_innerfuncs=[];
    function test_closing(){
        for(var inner=0;inner<10;inner++){
            testclosing_innerfuncs.push(function f() {
                console.log(inner);
            })
        }
    }

    var testavoidclosing_innerfuncs=[];
    function test_avoidclosing(){
        for(let inner=0;inner<10;inner++){
            testavoidclosing_innerfuncs.push(function f() {
                console.log(inner);
            })
        }
    }
    test();
    console.log("------------");

    test_closing();
    testclosing_innerfuncs.forEach(item=>{
        item();
    });
    console.log("------------");
    test_avoidclosing();
    testavoidclosing_innerfuncs.forEach(item=>{
        item();
    })


</script>
<body>

</body>
</html>

以上例子控制台输出:
在这里插入图片描述

其中第一个函数test()是普通函数,用于对比。
第二个函数test_closing是存在闭包的函数,虽然函数内部变量inner作用域只存在函数内循环体,但由于全局变量testclosing_innerfuncs的赋值引用,所以在执行test_closing函数时,仍然可以使用该内部变量,但由于闭包,调用时inner早已循环递加到10,所以输出10个10。
第三个函数test_avoidclosing是避免闭包对原始函数的影响,方法是让内部变量inner用let声明而不是var,let使变量只在作用域内有效,而不会存在于闭包所在的“气泡”(引自Secrets of the JavaScript Ninja)中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值