简体   繁体   中英

Whats the name for a javascript pattern with a variable that is assigned the return value of a function?

What the proper name of this Javascript pattern where a variable is assigned to value of a return function?

// array with a ton of random values. 
var once = (function(){

        var i = 10000, arr = [];

        while(i){
            arr.push( Math.random() * i );
            i--;
        }
        arr = arr.toString(); 

        return (function(){
            return arr;
        }());

}());

Edit - a better example:

 var once = (function(){

    // Only run a really expensive operation once...
    var i = 10000, arr = [], x;

    while(i){
        arr.push( Math.random() * i );
        i--;
    }
    arr = arr.toString(); 
    x = parseFloat(arr.toString());

    // then return the result of another function
    return function(){
        return x * (Math.random() * 10);
    };

}());

$(window).resize(function(){
    console.info(once());
});

That is a self-invoking anonymous function.

It is useful when you want to do some work, but keep the variables out of scope. This can be particularly important if you are worried about memory leaks - the variables used in the anonymous function go immediately out of scope, and can be cleaned up by the garbage collector. Of course, if you return a closure, the opposite happens - those variables remain for the life of the closure.

Edit: Your second example is a closure. Your closure looks a lot like your self invoking anonymous function, but, as I mentioned above, it behaves quite differently.

I'd go on a bit more about closures, but I'm answering from my phone, and that kind of an answer requires all ten fingers... maybe I'll come back to this later.

I believe you're looking for memoization .

In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs.

...

A memoized function "remembers" the results corresponding to some set of specific inputs. Subsequent calls with remembered inputs return the remembered result rather than recalculating it, thus eliminating the primary cost of a call with given parameters from all but the first call made to the function with those parameters.

Is it "currying"?

A function of N arguments that is considered as a function of one argument which returns another function of N-1 arguments.

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