0

I am using The Revealing Module Pattern with JS in an angular application.

Now I am going to migrate it from Javascript to Typescript, but I have no idea how to use this pattern with TS. I have read some other post like the following, but no one of them have the return at the beginning of the function. TypeScript code similar to Revealing Module Pattern structure

angular.module('app.services')
.factory('justAService', justAService);

function justAService() {

return {
  a: a
};

var x = {};

function a(){....}

Is it possible to write the return at the top?

Thank you

3
  • 1
    Don’t use that pattern; TypeScript has actual modules. developer.mozilla.org/en/docs/web/javascript/reference/… Commented Oct 13, 2016 at 15:46
  • 1
    Putting var x = {}; after the return also doesn’t make any sense. It will never be reached. It’s equivalent to declaring var x; and not initializing it. Commented Oct 13, 2016 at 16:06
  • Yes you are right. Why should a use modules instead of this pattern? Commented Oct 13, 2016 at 16:08

1 Answer 1

0

Yes it's possible. It's usually used to improve readability and it doesn't affect the program execution at all. Because function evaluation (definition) occur before that javascript gets executed, so when your module returns a reference to the function, it had already been defined. But it just works for functions declared this way, otherwise will be unreachable code.

Example:

module App{
    angular.module('app.services')
        .factory('justAService', justAService);

    function justAService() {

        return {
            a: a
        };

        function a() {

            var x = {};
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

May you show me a sample? I tried it but the function is always unreachable
What exactly have you tried? The given example seems to be on this situation.
I edited my sample. The code is pretty much like the sample
As I said in my answer it just work for function declarations, using a var x = {} will cause unreachable code. I've updated my answer with an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.