Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a closure and a module?

I know that a module like this one:

function User(){
    var username, password;

    function doLogin(user, pw){
        username = user;
        password = pw;
    };
    var publicAPI = {
        login: doLogin
    };
    return publicAPI;
}

has a closure inside of it: doLogin, and is remembering the values of the variables username and password that are inside User, what makes this a "closure". What I don't quite understand is if whenever we use a closure we are using the module pattern? or as soon as I save the function of the User in a variable like var User = function(){... is not a module... Please bear in mind I'm learning js.

like image 927
Camilo Sanchez Avatar asked Nov 20 '15 11:11

Camilo Sanchez


1 Answers

You have implemented a factory function for Users.

You are "almost" using the revealing module pattern. Most people would say the revealing module pattern would need to be invoked immediately. Module patterns are usually used for code organisation. What you have here instead is an object factory.

Closures are used by the (revealing) module pattern (and others) to achieve the encapsulation of private state.

A closure is created whenever a function is defined. They are a language feature of JavaScript to make working with functions easier.

like image 166
Ben Aston Avatar answered Oct 18 '22 23:10

Ben Aston