Home >Web Front-end >JS Tutorial >Introduction to the idea of js lazy function
Lazy function is another application of js functional programming. Lazy function means that the branch of function execution will only be executed when the function is called for the first time. This article will introduce the idea of js lazy function to everyone. I hope it will be useful to everyone. Some help.
Before vue, react and other frameworks are widely used, we need to use jQuery or native js to operate dom and write code. When using native js for event binding, we can The method to apply DOM2-level binding events is: element.addEventListener(). For compatibility, there is also:
element.attachEvent(). So we need to encapsulate it into a method:
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; } }
At this time, if an element needs to add multiple click events through one behavior, such as:
emit(div, 'click', fn1); emit(div, 'click', fn2);
Bind the fn1 event to the div for the first time Timing, it is already known which binding method the browser can perform. When executing binding fn2, there is no need to judge again, then the code can be modified:
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); }
In other words, we are doing the first After the first judgment, the function is redefined so that no judgment is needed when binding later. From a performance perspective, although a closure is created, it is better than making the same judgment multiple times in the future.
This is the lazy idea of functions. For the same judgment, we only need to perform it once.
This article comes from the js tutorial column, welcome to learn!
The above is the detailed content of Introduction to the idea of js lazy function. For more information, please follow other related articles on the PHP Chinese website!