<!DOCTYPE html>
<html>
<head>
<title>惰性函数</title>
</head>
<body>
<script type="text/javascript">
//正常的兼容性写法
function addEvent(el,type,handle){
if(el.addEventListener){
el.addEventListener(type,handle)
}else if{el.attachEvent}{
el.attachEvent(type,handle)
}else{
el['on' + type] = handle;
}
}
// 惰性函数的写法
// 函数有很多个分支判断,但这些分支判断只会在第一次调用时执行,
// 执行后会修改此函数,再次调用时无须判断
function addEvent(el,type,handle){
if(el.addEventListener){
addEvent = function (el,type,handle){
el.addEventListener(type,handle);
}
}else if(el.attachEvent){
addEvent = function (el,type,handle){
el.attachEvent(type,handle)
}
}else{
addEvent = function(el,type,handle){
el['on' + type] = handle;
}
}
}
</script>
</body>
</html>
No5-惰性函数
最新推荐文章于 2024-04-20 09:15:43 发布