标签:
重写自己如何减少判断?其实我也是学习别人的代码,才明白的。
具体代码:
//兼容的绑定事件方法 function addHandler(target, eventType, handler) { //重写自己 if (target.addEventListener) { //DOM2 Events addHandler = function (target, eventType, handler) { target.addEventListener(eventType, handler, false); }; } else { //IE addHandler = function (target, eventType, handler) { target.attachEvent("on" + eventType, handler); }; } //关键,调用新方法,重写自己,减少判断,第二次调用时,使用新方法,没有判断 addHandler(target, eventType, handler); } function removeHandler(target, eventType, handler) { //o//重写自己 if (target.removeEventListener) { //DOM2 Events removeHandler = function (target, eventType, handler) { target.addEventListener(eventType, handler, false); }; } else { //IE removeHandler = function (target, eventType, handler) { target.detachEvent("on" + eventType, handler); }; } //关键,调用新方法,重写自己,减少判断,第二次调用时,使用新方法,没有判断 removeHandler(target, eventType, handler); }一般人的写法是这样:
function addHandler(target, eventType, handler) { if (target.addEventListener) { //DOM2 Events target.addEventListener(eventType, handler, false); } else { //IE target.attachEvent("on" + eventType, handler); } }
标签:
原文地址:http://blog.csdn.net/xuexiaodong009/article/details/51832056