This article describes the method of calling functions as parameters in JavaScript. Share it for your reference. The specific analysis is as follows:
Let’s take a look at the 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 of execution of this code is: interpret execution from top to bottom, which is the JS provision.
Here we mainly explain how the function in m.eachMap() is passed and executed as a parameter:
step1: When executing the m.eachMap method, JS will look for the corresponding this.eachMap method;
step2: Find this.eachMap method and will be executed according to the order of statements in the function body;
step3: When it is executed to fn(attr, obj[attr]);, it will return to the for statement execution; note that before the return for statement execution, attr has no value; after returning from the for statement, the value of attr has been found, which is '01', and the value of obj[attr] has also exists, which is 'abc';
step4: Then, fn(attr, obj[attr]); will be returned to the parameter function of m.eachMap method, that is,
function(key, value){alert(key + " : " + value);}attr replaces key, obj[attr] replaces value, and executes alert statement, output.
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.