简体   繁体   中英

Using closures in node js

What is the difference in the use of the below methods?

First Method :

for(var i = 0; i < 10; i++) {
    (function(e){
        setTimeout(function() {
            console.log(e); 
        }, 1000);
    })(i);
}

for(var i = 0; i < 10; i++) {
    createTimeoutFunction(i);
}

Second Method :

function createTimeoutFunction(e){ 
    setTimeout(function() {
        console.log(e); 
    }, 1000);
}

for(var i = 0; i < 10; i++) {
    createTimeoutFunction(i);
}

I am new to node js and in using closures. Though both methods return the same output but the second method runs with error. I am not understanding why do we need to use two loops as in the first method. Can't we just execute as like the second method?

Remove the second for in your first method, because unless you want the loop to run twice, it is redundant as everything is already happening in the first. The second loop fails because createTimeoutFunction is never defined outside of the scope of the first loop, as opposed to the second method.

Other than that, they both will produce the same result, the only difference being in the second method createTimeoutFunction is reusable.

See also: How do JavaScript closures work?

A closure in javascript works the same regardless of the environment or interpreter that you're using.

A closure provides a specific variable scope in which that set of code executes. Your closure will have access (obviously) to anything defined within itself, as well as any objects defined in any enclosing closure.

The problem with you code up there is that in the first example createTimeoutFunction isn't defined anywhere -- when you call it it will fail. In that example:

(function(e){
    setTimeout(function() {
        console.log(e); 
    }, 1000);
})(i);

The function being defined within this closure is an anonymous function. It has no name property and can't be referenced.

The second version defines a global variable createTimeoutFunction which is then accessible in ANY closure on the page since it's part of the global object. (Well I'm assuming that since you're not showing that this code is enclosed by anything else).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM