对与javascript来说,如果不懂闭包,都不好意思说自己会javascript,下面先写一个关于闭包的一个应用.
在c++中,我们常会如此初始化一个只需在程序启动时初始化的变量:
1 #include <iostream> 2 3 int LocalStatic(); 4 void main(int argc,char* argv[]){ 5 int local = LocalStatic(); // local=1 6 local = LocalStatic(); // local=2; 7 }; 8 9 10 int LocalStatic(){ 11 static int local = 0; 12 return ++local; 13 }
其实在javascript中,也可以通过闭包来实现类似的效果.
比如我需要在页面加载的时候获取页面的高度和宽度,一般我们写一个方法:
1 function layout () { 2 var page = null; 3 if (document.compatMode == "BackCompat") { 4 page = { width: Math.max(document.body.scrollWidth, document.body.clientWidth), height: Math.max(document.body.scrollHeight, document.body.clientHeight) }; 5 } else { 6 page = { width: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth), height: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) }; 7 } 8 return page; 9 }
虽然例子中的场景并不适用,但是,每次都要去重复的做一些初始化变量的操作.换成下面的代码则利用了闭包的特性巧妙的绕过去了.
var layout = function (){ var page; return function(){ if(!page){ if (document.compatMode == "BackCompat") { page = { width: Math.max(document.body.scrollWidth, document.body.clientWidth), height: Math.max(document.body.scrollHeight, document.body.clientHeight) }; } else { page = { width: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth), height: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) }; } } return page; }; }();