Unleash the Power of Autoexecuted Objects in JavaScript

0 0
Read Time:59 Second

Sometimes you will need to create autoexecuted object (for example in case of load/document ready events).

Have you tried to do it this way?

(function() {
        // Elements
        var z;

        // Private methods
        var internalObj = {

            init: function() {
                console.log('init')
            }
        };

        // Autoinvoking constructor
        (function() {
            console.log('start');
            internalObj.init();

        })();

    })();

Autoexecuted object

So what will you do if you want to have external API to your “autoexecuted object”? You can do it this way:

var auto = (function() {
        // Elements
        var z;

        // Private methods
        var internalObj = {

            init: function() {
                console.log('init')
            }
        };

        // Autoinvoking constructor
        (function() {
            console.log('start');
            internalObj.init();

        })();
        return { initObj: internalObj.init}

    })();

auto.initObj();

Currently we are creating variable to which we are assigning an object. This object return an API with one method which is equal an internalObject init method.

But what we can do if we do not ant to do it this way and we don’t want to create any new object assigned to variable?

(function() {
        // Elements
        var z;

        // Private methods
        var internalObj = {

            init: function() {
                console.log('init')
            }
        };

        // Autoinvoking constructor
        (function() {
            console.log('start');
            internalObj.init();

        })();
        this.init = internalObj.init;

    })();

init();

So this.init = internalObj.init assigns to window (global) function a function from our internalObj – init.

About Post Author

Piotr Sikora

Piotr Sikora Founder of WolePapierowe.com Co-founder of Liderazgo.pl MeetJS Kielce Committee member. JavaScript and Python enthusiast.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

© UiCore 2024. All Rights Reserved.