zoukankan      html  css  js  c++  java
  • 闭包的一些例子

    1.闭包允许将函数与其所操作的某些数据(环境)关连起来。这显然类似于面向对象编程。在面向对象编程中,对象允许我们将某些数据(对象的属性)与一个或者多个方法相关联。

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style type="text/css">
            body{
                font-size: 12px;
            }
            h1{
                font-size: 1.5em;
            }
            h2{
                font-size: 1.2em;
            }
        </style>
        <script type="text/javascript">
    
            window.onload=function(){
            function makeSizer(size){
                return function(){
                    document.body.style.fontSize=size+'px';
                };
            }
            var size12=makeSizer(12);
            var size14=makeSizer(14);
            var size16=makeSizer(16);
            document.getElementById('size-12').onclick=size12;
            document.getElementById('size-14').onclick=size14;
            document.getElementById('size-16').onclick=size16;
        }
        </script>
    </head>
    <body>
        <p>test</p>
        <h1>i love you</h1>
        <h2>i hate you</h2>
        <a href="#" id="size-12">12</a>
        <a href="#" id="size-14">14</a>
        <a href="#" id="size-16">16</a>
    </body>
    </html>

    2.使用闭包模拟私有方法

    var makeCounter=function(){
        var privateCounter=0;
        function changeBy(val){
            privateCounter+=val;
        }
        return {
            increment: function(){
                changeBy(1);
            },
            decrement: function(){
                changeBy(-1);
            },
            value: function(){
                return privateCounter;
            }
        }
    };
    var Counter1=makeCounter();
    Counter1.increment();
    console.log(Counter1.value());
    Counter1.decrement();
    console.log(Counter1.value());
    Counter1.increment();
    console.log(Counter1.value());
  • 相关阅读:
    alias这个命令还是很有用的
    为什么不推荐用破解版的winrar
    chrome headless
    关于PDF的一些书籍
    PDF的一些工具
    3DPDF是个什么东西?
    你可能不知道的pdf的功能
    为什么一些公司把dwg文件转化为pdf
    关于pdf阅读器的选择
    接外包怎么保护自己的作品
  • 原文地址:https://www.cnblogs.com/ybleeho/p/7636792.html
Copyright © 2011-2022 走看看