2

Recently I've been getting into Anonymous functions in a big way and wondering how this is possible as I'm trying to re-arrange my JS code-base.

(function (listLoad, $, undefined) {
    listLoad.create = function(data)
    {
        this.init = function(data)
        {
        }
    } 
} (window.listLoad = window.listLoad || {}, jQuery));

What I'm looking to do is obviously have a number of functions for my "listLoad" page, such as "dataMap" etc, in which will all have init functions for initializing the page.

My main question is how do I access this .init function? I'm guessing it's of private scope. I've tried:

listLoad.create.init = function(data)

and

 create.init = function(data)

and even init = function(data)

All to no success when writing

listLoad.create.init();

How to do this? I'm more than happy to hear certain suggestions on architecture too if you feel I'm going the wrong way about my scenario.

1 Answer 1

3

In fact your syntax for anonymous function is not complete.

First you must execute the annonymous block with ending parentheses:

(function (...) {
    ...
})(...)

Inside the block, your code could be improved this way:

var listLoad = {};

(function (x) {
    x.create = {
        init: function(data) {
            console.log('plop');
        }
    }
})(listLoad);


listLoad.create.init()

This provoke plop to appear logged into the console.

Sign up to request clarification or add additional context in comments.

1 Comment

That's amazing, thank you! For reference, my anon function was executing, but I needed to change the syntax to listLoad.create = { init: function(data) { } } Once again, thank you!

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.