Is this a valid use case for javascript closure?

Viewed 237

I have looked through all the other (excellent) answers on SO (especially this: How do JavaScript closures work?) but I wanted your feedback on my understanding of the concept.

I understand that one use case is to hide the implementation of private methods from public access.

The other one that I think of is having it as a factory generator:

<script>

function carFactory( make ) {

    var m = make;
    return { manufacture: function ( model ) 

        {console.log("A " + m + " " + model + " has been created");}

    }
}

toyotaFactory = carFactory("toyota");
hondaFactory = carFactory("honda");

toyotaFactory.manufacture("corolla");
toyotaFactory.manufacture("corolla");
hondaFactory.manufacture("civic");

</script>

This outputs:

A toyota corolla has been create
A toyota corolla has been created
A honda civic has been created 

So do you think its a valid use case for closures (i.e. creating multiple factories using the same code base)? Or can I achieve the same thing using something much better?

Please note that the question is less about the technical implementation of closures and more about valid use cases in application design / development.

Thanks.

4 Answers

I was trying to come up with a practical example of information-hiding/encapsulation and this is what my attempt so far

'use strict';

const bank = (accountHolderName, initialDeposit) => {
    let balance = initialDeposit;
    const add = (amount) => {
        balance += amount;
    }

    let subtract = (amount) => {
        balance -= amount
    }

    let printBalance = () => {
        console.log(accountHolderName, "has balance of", balance, "dollars");
    }

    return {
        credit: add,
        debit: subtract,
        balance: printBalance
    }
}

let amy = bank("Amy", 1000);
amy.balance();
amy.credit(100);
amy.balance();
amy.debit(10);
amy.balance();

let sam = bank("Sam", 50);
sam.balance();
sam.credit(50);
sam.balance();
sam.debit(100);
sam.balance();

Once you run, you would get the following output

Amy has balance of 1000 dollars
Amy has balance of 1100 dollars
Amy has balance of 1090 dollars
Sam has balance of 50 dollars
Sam has balance of 100 dollars
Sam has balance of 0 dollars

The benefits?

  • the balance variable is not directly accessible.
  • Using closures, every caller get's their own data. Amy's balance is not interfering with Sam's data
  • The callers (Amy, Sam, and others) has a nice API to work with instead of worrying about the internal details on how bank operates.

Am I missing something else?

Related