Question

More and more javascript has this modular approach where empty functions are returned. You can find it in the source of node.js. It's in the documentation of require.js. What does it do?

define(['jquery'] , function ($) {
    return function() {};
});

If I would return an object, I would just do return {};, although I see no use in returning an empty object. Might wanna put the vars in it. So there is obviously something valuable about this. I'm guessing it has something to do with accessing functions that were in the scope of the returned function.

Here is that construction again, in the AMD Is Not The Answer article:

define(['dep1', 'dep2'], function (dep1, dep2) {
    //Define the module value by returning a value.
    return function () {};
});

But what is the practical benefit above in stead of just returning the semantically meaninful stuff you want to return, e.g. in an object?

And how do you access outside-function-inside-scope things in this way?

function(baz) {
    var foo = true,
        bar = false;

    if (baz) bar = true;

    return function() {}; // wut?
};

Although I am not exactly technically 'challenged', I was hoping someone could explain this in layman's terms, because articles about modularity do not make me happy.

Was it helpful?

Solution

You have got your code wrong. It should be self executing function like this:

(function(baz) {
    var foo = true,
        bar = false;

    if (baz) bar = true;

    return function() {}; // wut?
});

So you just forgot ( in front of it. Now you probably will use it as an expression so it will become like this

var singleton = (function(baz) {
    var foo = true,
        bar = false;

    if (baz) bar = true;

    return function() {}; // wut?
});

Now your singleton variable will be a simple empty function.

If you put in

return function() {
  return foo; 
}

it becomes useful as this: singleton() <- returns true

And is very similar to module pattern where you just write:

return {
  myFoo: foo
}

And so you can access it with singleton.myFoo;

This is useful to implement public/private variables so you just return functions/variables you want to expose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top