Search code examples
javascriptfunctionobjectmethodsself-reference

Call method from within itself?


I have this snippet:

myApp.factory('productsStore', function ($http, $q, Product) {
    var products = "";

    products = productsStore.get();

    return {
        get: function () {
            return Product.query({});
        }
    };
});

How can I call the get() method, from within the same 'factory'? products = productsStore.get() does not work obviously.


Solution

  • You can use the Revealing Module Pattern:

    myApp.factory('productsStore', function ($http, $q, Product) {
        var products = "";
    
        var get = function () {
            return Product.query({});
        };
    
        products = get();
    
        return {
            get: get
        };
    });
    


    Reasons I enjoy this pattern:

    • No cluttering with this., MyObject., etc. prefixing.
    • You see clearly in the bottom return what is publicly exposed.


    A great article on the subject: Mastering the Module Pattern