Search code examples
angularjsfactoryencapsulation

Angular js - Hide private variables from factories


Pls refer - http://jsfiddle.net/36qp9ekL/629/

I am using a factory method so that i can hide the implementation logic, private(pvt) variables and all the pros that factories are meant for.

If you run the code and see the console, I am able to view pvtvar1 and pvtvar2. How do I actually hide the pvt variables, implementation details.

app.controller("mycontroller", function($scope, myfactory) {

console.log(myfactory);

});

If you could tell the advantages of factories over services, would be helpful.


Solution

  • As you know, there are no privates in javascript. You are using closure to create inaccessible variables and functions. This is as good as you'l get. The console may show you (depending on the browser) properties that are defined via closure, but the important thing is, these properties aren't accessible in your code.

    Advantages of a service over a factory? You can create an injectable service from a js object instead of a function so you can create services that inherit functionality. Not terribly useful since the injectable model is a replacement for inheritance in many ways but it's still an option.

    I exclusively write services instead of factories but I'm using typescript in my projects (which has privates ;))