打赏

JavaScript创建块级作用域

1、JavaScript创建块级作用域

(1)方法一:ES6

(2)方法二:闭包

 

2、示例

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

    <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>JavaScript创建块级作用域</title>
    </head>

    <body>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <script>
            var li = document.getElementsByTagName('li');
            //方法一:ES6创建块级作用域
            function closure() {
                for(let i = 0, len = li.length; i < len; i++) {
                    li[i].onclick = function() {
                        console.log(i)
                    }
                }
            }
            //方法二:使用闭包创建块级作用域
            function closure2() {
                for(var i = 0, len = li.length; i < len; i++) {
                    li[i].onclick = (function(i) {
                        return function() {
                            console.log(i)
                        }
                    })(i);
                }
            }
            closure();
            closure2();
        </script>
    </body>

</html>

 

posted @ 2018-03-26 11:41  孟繁贵  阅读(529)  评论(0编辑  收藏  举报
TOP