Ryan
Ryan

Reputation: 10049

Javascript, calling function

from previous help I am using something like this:

(function (global) {

  // your code here

  global.myGlobalVar = myVar

}(this));

which works great for variables, but how do I do it for functions?

For example I tried this:

(function (global) {

  function something()
{
// do something, return something
}

  global.something()= something();

}(this));

but that does not work :(

How do I get it to work with functions?

Thanks!

EDIT:

Please note that this is being called in a html page, first I do this:

<script language="Javascript" src="four.js">

then

<body onload="javascript:something()">

Upvotes: 1

Views: 2466

Answers (3)

Justin M. Keyes
Justin M. Keyes

Reputation: 6964

(function (global) {

  global.something = function()
  {
    // do something, return something
  }

}(this));

Updated question:

<body onload="javascript:something()">

This won't work. Try this instead:

<body onload="something()">

Upvotes: 1

pimvdb
pimvdb

Reputation: 154818

If you want to declare a function, you should not execute it. So remove ().

(function (global) {

  function something()
{
// do something, return something
}

  global.something = something; // something is the variable
                                // containing the function and
                                // you store it into global


}(window));

Upvotes: 5

kapa
kapa

Reputation: 78671

In Javascript, a function can be stored in a variable (as it is an object basically).

You could do something like this using a closure:

(function (global) {

  global.something= function () {
      // do something, return something
  };

}(this));

Remember, if you write () after a function name, it means you're executing it. If you want to pass the function itself, you simply write its name.

Consider this example:

var x = something(); //x will hold the RETURN value of 'something'
var y = something; //y will hold a reference to the function itself

So after doing the 2nd example, you could do: var x = y(); which will actually give you the same result if you just simply did the 1st example.

Upvotes: 4

Related Questions