码迷,mamicode.com
首页 > 其他好文 > 详细

闭包的一些例子

时间:2017-10-08 12:16:23      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:面向对象编程   val   console   counter   编程   例子   onload   element   ret   

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

 

闭包的一些例子

标签:面向对象编程   val   console   counter   编程   例子   onload   element   ret   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!