首页 > 其他 > 详细

闭包的一些例子

时间:2017-10-08 11:50:43      阅读:193      评论:0      收藏:0      [点我收藏+]

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());

 

闭包的一些例子

原文:http://www.cnblogs.com/ybleeho/p/7636792.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!