Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner(Private) Functions and Closures

Tags:

javascript

Would some enlighten on the difference of Inner(Private) functions and Closures, as they appear very similar.

Inner Function:

function a(param) {
    function b(theinput) {
        return theinput * 2;
    };
    return 'The result is ' + b(param);
};

Closure

function f() {
    var b = "b";
    return function () {
        return b;
    }
}
like image 983
Wasabi Avatar asked Dec 28 '22 16:12

Wasabi


1 Answers

Your second example explicitly returns a function object which maintains a link to the variables within the function which returned it, while your first example simply returns the result of invoking a private function. So the second example is of closure.

Here's a slightly modified version of your second example which better demonstrates a closure:

function f(){
    var a = "foo";

    // return an object containing two methods
    // which can access and modify the private "a"
    // variable even after the function has returned
    return {
        showA: function() {
          alert(a);  
        },
        changeA: function(str) {
            a = str;
        }  
    }   
}

var fun = f();
fun.showA(); // "foo"
fun.changeA("blahblah"); 
fun.showA(); // "blahblah"

Fiddle: http://jsfiddle.net/MKD6p/1

So as you can see, the stack frame has not been deallocated after the function has returned; the variables inside are kept alive and can be played with by means of a suitable interface.

Your first example's inner function does have access to its outer scope, and does return a value based on a variable declared in its outer function/scope/closure. But since a function or module has not been returned the variables local to the function are deallocated once the (outer) function has returned - so, while the the inner function does form a closure with its outer scope, it does not really serve as a productive example of what a closure is.

like image 161
karim79 Avatar answered Jan 08 '23 07:01

karim79