18. Callback mode in javascript:
Shape:
Function writeCode (callback) {// execute some things, callback ();//...} function intrduceBugs (){//.... introduce vulnerability} writeCode (intrduceBugs); we pass the function application to writeCode (), so that writeCode can be executed when appropriate (called after return)
Let's take a look at a very bad example (we need to refactor it later ):
// Simulate the dom node on the page and return the nodes in the array. // This function is only used to find the nodes that do not perform any logic processing on the dom node. var findNodes = function () {var I = 100000; // a large number of loops, var nodes = []; // used to store the found dom node var found; while (I) {I-= 1; nodes. push (found);} return nodes;} // hide all the dom nodes found in the search. var hide = function (nodes) {var I = 0, max = nodes. lenght; for (; I
The above method is inefficient, thinking that hide () must traverse the array nodes returned by findNodes () again. How can this redundant loop be avoided.
We cannot directly hide the queried node in findNodes (in this way, we can modify the logic coupling for the search), so it is no longer a common function.
The solution is to use the callback mode. You can pass the node hiding logic to findNodes () in the callback function mode and entrust it to execute.
// Refactor findNodes to accept a callback function var findNodes = fucntion (callback) {var I = 100000, nodes = [], found; // check whether the callback function can be called if (typeof callback! = 'Function') {callback = false;} while (I) {I-= 1; if (callback) {callback (found);} nodes. push (found);} return nodes;} // callback function var hide = function (node) {node. style. display = 'none';} // locate the subsequent node and hide it in subsequent execution
FindNodes (hide); // first execute findNodes and then execute hide. Of course, the callback function can also be created when calling the main function: findNodes (function (node) {node. style. display = 'none ';});