Methods for calling functions as parameters in JavaScript _javascript tips

Source: Internet
Author: User

The examples in this article describe the methods that functions in JavaScript invoke as arguments. Share to everyone for your reference. The specific analysis is as follows:

First look at the example:

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 (' The ', ' abc ');
M.put (' A ', 1024);
M.put (', true ');
M.put (' 0 ');
M.put (' A ', false);

M.eachmap (function (key, value) {
alert (key + ":" + value);
});

The order in which this code is executed is: to interpret execution from the top down, which is the rule of JS.
Here is a description of how the function in M.eachmap () is passed and executed as a parameter:

Step1: The implementation to m.eachmap this method, JS will go to find the corresponding this.eachmap this method;
Step2: Find the This.eachmap method, which is executed according to the order of the function body;
Step3: When executed to FN (attr, obj[attr]), he will return to the For statement execution; Note that attr is not a value until the return for statement is executed; After returning from the for statement, the attr value is ' 01 ', and Obj[attr] The value also has, for ' ABC ';
Step4: Then FN (attr, obj[attr]) will return to the parameter function of M.eachmap this method, i.e.

function (key, value) {
alert (key + ":" + value);
}

Attr replaces key,obj[attr] to replace value and execute alert statement, output.

STEP5: Continue to execute the For loop, repeat the STEP4, and output until the end.

I hope this article will help you with your JavaScript programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.