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