Monday, April 25, 2011

Javascript : Self-invoking functions : function() { } ();

A self invoking function is one that's invoked as soon as it's declared.
They are they run immediately upon read by the browser.

Understanding this concept will help you to understand closure in javascript.

[code : javascript ]
 var obj = function () {
            var private1 = 1;
            var private2 = 2;

            var priv_func = function () {
                alert(private1);
            }

            return {
                public1: 'one',
                public2: 'two',

                pub_func: function () {
                    alert(this.public1);
                    alert(private2);
                }
            };

        }
 [code : html]
<input type="button" value="click me" onclick="obj.pub_func();" />

If you run the above example you will probably receive an error message like " Object doesn't support property or method 'pub_func'". The reason being the object is not created yet.

Well, we have a solution to this problem in javascript in the form of "self invoking function". We will need to get the browser invoke it as soon as it is definded by insert "( );" at the end of the function.


 [code : javascript ]
 var obj = function () {
            var private1 = 1;
            var private2 = 2;

            var priv_func = function () {
                alert(private1);
            }

            return {
                public1: 'one',
                public2: 'two',

                pub_func: function () {
                    alert(this.public1);
                    alert(private2);
                }
            };

        } ();

No comments:

Post a Comment