Search code examples
javascriptself-invoking-function

Javascript - How to invoke a method inside self invoking function?


In the below code

(function x() {
var j = function() { alert("234234"); }
return {
    s: j
}
})()

var x1 = new x();
x1.s();

How to invoke the method j()? Or before that i should be asking, is there a way to create an instance of the function x() because that is what is happening. Please see the fiddle http://jsfiddle.net/e5k6bdvn/


Solution

    1. Don't give the self invoking function a name (there is little benefit to it beyond making it easier to find in a stacktrace, which you shouldn't need at that point, and it memory leaks in old IE)
    2. Don't call the self invoking function twice
    3. Don't treat the self invoking function as if it was a constructor function (by calling it with new)
    4. Do capture the return value of the self-invoking function

    Such:

        var x = (function () {
            var j = function() { alert("234234"); };
            return {
                s: j
            };
        })();
        
        x.s();


    Or, if you want to create multiple objects in the same way:

    1. Don't use a self-invoking function
    2. Do call x as many times as you like

    Such:

        function x () {
            var j = function() { alert("234234"); };
            return {
                s: j
            };
        };
    
        var x1 = x();
        var x2 = x();
        x1.s();


    Or, if you want to create a constructor function:

    1. Don't return anything from it
    2. Do use the prototype chain

    Such:

        function x () {
        };
    
        x.prototype.s = function () {
            alert("234234");
        }
        
        var x1 = new x();
        var x2 = new x();
        x1.s();