1

I have function expression in javascript like this:

(function () {
    .
    //code here
    .
    .
}());

how do I call it from somewhere else like from another function.

I have tried this.

var bind = (function () {
    //code here...//
}());

and called it in some other function like

bind();

or

new bind();

or

var b = new bind();

but it doesn't work. How can I fix this?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Salim
  • 143
  • 11

1 Answers1

0

With this statement:

var bind = (function () {
    //code here...//

    return 42;
}());

bind variable is not assigned to that function. Instead, it is assigned with the returned value of the immediate function. So you will get bind = 42.

To define a function with immediate function

You may want to create a function inside the immediate function (which may compose a closure if you want) and returns it for later use. See the example below:

var bind = (function() {
    function B(){
        // do something
        return 42;
    }
    return B;
}());

bind(); // <-----bind is a B(), so invoke it will return 42

This will potentially create a function from the immediate function and assigns it the the bind variable so you can invoke it later.

TaoPR
  • 5,932
  • 3
  • 25
  • 35