The example in this article describes the method of calling functions as parameters in JavaScript. Share it with everyone for your reference. The specific analysis is as follows:
Let’s look at an example first:
function Map(){ var obj = {}; this.put = function(key, value){ obj[key] = value; } this.eachMap = function(fn){ for(var attr in obj){ fn(attr, obj[attr]); } } } var m = new Map(); m.put('01', 'abc'); m.put('02', 1024); m.put('03', true); m.put('04', 0); m.put('05', false); m.eachMap(function(key, value){ alert(key + " : " + value); });
The order in which this code is executed is: interpreted and executed from top to bottom, which is a requirement of JS.
Here we mainly explain how the function in m.eachMap() is passed and executed as a parameter:
step1: When the m.eachMap method is executed, JS will find the corresponding this.eachMap method;
step2: Find the method this.eachMap and it will be executed according to the order of statements in the function body;
step3: When fn(attr, obj[attr]); is executed, it will return to the for statement execution; note that before returning to the for statement execution, attr has no value; after returning from the for statement, the value of attr is Yes, it is '01', and the value of obj[attr] is also there, it is 'abc';
step4: Then, fn(attr, obj[attr]); will return to the parameter function of the m.eachMap method, that is,
function(key, value){ alert(key + " : " + value); }
attr replaces key, obj[attr] replaces value, and executes the alert statement and outputs it.
Step5: Continue to execute the for loop, repeat step4, and output until the end.
I hope this article will be helpful to everyone’s JavaScript programming design.