高阶函数 - 惰性加载函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>高阶函数 - 惰性加载函数</title>
</head>
<body>
    <div style="width: 100px; height: 100px; background: #f60;" id="div1"></div>
    <script>
        /**
         * 根据作用域链内部会重写外部的addEvent变量(如果在1. 2.处, 在addEvent前加上var就不是惰性了)
         */
        var addEvent = function(ele, type, handler) {
            if (window.addEventListener) {    // 标准
                addEvent = function(ele, type, handler) {    // 1.
                    ele.addEventListener(type, handler, false);
                };
            } else if (window.attachEvent) {
                addEvent = function(ele, type, handler) {    // 2.
                    ele.attachEvent('on' + type, handler);
                };
            };
            addEvent(ele, type, handler);
        };

        var div = document.querySelector('#div1');
        addEvent(div, 'click', function() {
            console.log(111);
        });

        addEvent(div, 'click', function() {
            console.log(222);
        })

    </script>
</body>
</html>

 

posted @ 2017-07-11 16:50  Sorrow.X  阅读(215)  评论(0编辑  收藏  举报