惰性函数是js函数式编程的另一个应用,惰性函数表示函数执行的分支只会在函数第一次调用的时候执行,他的应用情景在于当我们遇到一个需要判断场景去调用不同的方法时,避免重复进入函数内的if判断,也就是说if判断只进行一次,之后函数就会被分支里的代码替换掉
我们先看个例子
???????function a(){ ??????????????console.log("this is a"); ??????????} ??????????function a(){ ??????????????console.log("this is other a"); ??????????} ??????????a(); //输出this is other a ???????//同名函数被覆盖
在js中,不能存在同名函数,因为在创建词法作用域时,函数声明就会被提前,所以上面的例子中只输出this is other a。
我们再看下面这个例子
??????????????function b(){ ??????????????console.log(‘b‘); ??????????????b1 = function(){ ??????????????????console.log(‘other b‘); ??????????????} ??????????} ??????????b(); // 执行第一个b函数 ??????????b1();// 执行第二个函数
我们可以看见这里执行了连个函数,b和b1 如果把b1换成b的话,我们就可以达到重写b的目的,利用这步,我们就可以得到惰性函数
?function person(name){ ???????????????if(name=="jack"){ ???????????????????return ?person = function(){ ???????????????????????console.log("this is jack"); ???????????????????} ???????????????}else if(name == "tom"){ ???????????????????return person = function(){ ???????????????????????console.log("this is tom"); ????????????????????} ???????????????????}else{ ???????????????????return person = function(){ ???????????????????????console.log("this is others"); ???????????????} ???????????} ???????????????} ???????????????person("jack")(); ???????????????console.log(1); ???????????????person();
这里我们可以看出来,当第一次执行完person函数后,他就被后面的person函数替代了,此时的person函数只剩下console这个输出了,这里就是一个惰性函数的小例子
那么惰性函数的实际应用在那里呢,我们可以从实际的dom操作中感受,添加监听事件的方法有两种,ie和其他的
function addEvent(type, element, fun) { ???if (element.addEventListener) { ???????element.addEventListener(type, fun, false); ???} ???else if(element.attachEvent){ ???????element.attachEvent(‘on‘ + type, fun); ???} ???else{ ???????element[‘on‘ + type] = fun; ???}}
这个函数会在每次运行时根据浏览器的不同选定相应的监听器,但每次运行时所有的代码都要跑一遍,这明显不够好,我们可以利用函数重写,当函数第一次运行时,我们就判断出来了浏览器支持哪种监听器,以后只要将方法替换当前的方法就可以了
function addEvent(type, element, fun) { ???if (element.addEventListener) { ???????addEvent = function (type, element, fun) { ???????????element.addEventListener(type, fun, false); ???????} ???} ???else if(element.attachEvent){ ???????addEvent = function (type, element, fun) { ???????????element.attachEvent(‘on‘ + type, fun); ???????} ???} ???else{ ???????addEvent = function (type, element, fun) { ???????????element[‘on‘ + type] = fun; ???????} ???} ???return addEvent(type, element, fun);}
如上,就可以实现惰性函数的特性,只执行一次。
js之惰性函数
原文地址:https://www.cnblogs.com/maoxiaodun/p/10125081.html