maze star
maze star

Reputation: 11

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/

Upvotes: -1

Views: 2951

Answers (2)

Giuseppe Crinò
Giuseppe Crinò

Reputation: 546

As stated by @epascarello, it's hard to say what is the context of your question.

If the meaning of x is to return objects more than once, you should not immediately invoke it. Instead you need only to declare it:

function x () { return { j: function () { alert("234234") } } }

then call it whenever you want, and invoke j.

var x1 = x();
x1.j();

If instead you're planning to use x only once, it's nice to invoke it immediately, but you need to consume the call to j immediately too.

(function () {
    return {
        j: function () {
            alert("234234")
        }
    }
})().j();

Upvotes: 1

Quentin
Quentin

Reputation: 943100

  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();

Upvotes: 8

Related Questions