Home > Web Front-end > JS Tutorial > body text

How to call functions as parameters in javascript_javascript skills

WBOY
Release: 2016-05-16 16:15:09
Original
1350 people have browsed it

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);
});
Copy after login

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);
}
Copy after login

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.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!