let getTime = () => {
var time = Date.now()
getTime = () => {
return time
}
return getTime()
}
console.log(getTime());
console.log(getTime());
console.log(getTime());
上面的代码固然可以通过闭包啥的来解决 但是这里表示一个思想 惰性函数是在第一次运行时根据不同的分支 再次修改函数自身 下次运行的时候就不需要经过之前的分支
简单的说就是一次性改变了自身,形成了新的函数
比如下面的对浏览器的dom绑定事件的判断
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="btn">点击</button>
<div class="btn">点击</div>
<script>
const btn = document.getElementsByClassName('btn')[0]
const div_btn = document.getElementsByClassName('btn')[1]
function bindEvent(el,type,fn,capture){
if(el.addEventListener){
bindEvent = function (el,type,fn,capture){
el.addEventListener(type,fn,capture)
}
}else if(el.attachEvent){
bindEvent = function(el,type,fn){
fn.call(el)
}
}else{
bindEvent = function (el,type,fn,capture){
el['on'+ type] = fn
}
}
bindEvent(el,type,fn,capture)
}
function fn1(){
console.log(this);
console.log('bindEvent',bindEvent);
}
bindEvent(btn,'click',fn1,false)
bindEvent(div_btn,'click',fn1,false)
</script>
</body>
</html>
|