在vue、react等框架大量应用之前,我们需要使用jQuery或者原生js来操作dom写代码,在用原生js进行事件绑定时,我们可以应用DOM2级绑定事件的方法,即:元素.addEventListener(),因为兼容性,还有:
元素.attachEvent()。所以我们需要封装成一个方法:
function emit(element, type, func) {
if (element.addEventListener) {
element.addEventListener(type, func, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, func);
} else { //如果不支持DOM2级事件
element['on' + type] = func;
}
}
这个时候,如果一个元素需要通过一个行为添加多个点击事件,如:
emit(div, 'click', fn1); emit(div, 'click', fn2);
在第一次给div进行fn1事件绑定时,已经知道浏览器可以执行哪种绑定方式,执行绑定fn2时,就没有必要再次进行判断,那么代码可以进行修改:
function emit(element, type, func) {
if (element.addEventListener) {
emit = function (element, type, func) {
element.addEventListener(type, func, false);
};
} else if (element.attachEvent) {
emit = function (element, type, func) {
element.attachEvent('on' + type, func);
};
} else {
emit = function (element, type, func) {
element['on' + type] = func;
};
}
emit(element, type, func);
}
也就是说,我们在进行第一次判断后,对函数进行重新定义,这样在之后再进行绑定时不需要再进行判断,从性能角度讲,虽然创建了闭包,但优于后续进行多次同一个的判断。
这就是函数的惰性思想,对于同一个判断,我们只需要进行一次就好。
来源:https://www.cnblogs.com/ronaldo9ph/p/12299265.html