Javascript,调用函数

Rya*_*yan 1 javascript function global-variables

从以前的帮助我使用这样的东西:

(function (global) {

  // your code here

  global.myGlobalVar = myVar

}(this));
Run Code Online (Sandbox Code Playgroud)

哪个适用于变量,但我如何为函数执行此操作?

例如我试过这个:

(function (global) {

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

  global.something()= something();

}(this));
Run Code Online (Sandbox Code Playgroud)

但那不起作用:(

如何让它与函数一起使用?

谢谢!

编辑:

请注意,这是在html页面中调用的,首先我这样做:

<script language="Javascript" src="four.js">
Run Code Online (Sandbox Code Playgroud)

然后

<body onload="javascript:something()">
Run Code Online (Sandbox Code Playgroud)

pim*_*vdb 5

如果要声明函数,则不应执行它.所以删除().

(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));
Run Code Online (Sandbox Code Playgroud)

  • 为了比较:`(function(){return this;}());`返回`window`,而`(function(){'use strict'; return this;}());`返回`undefined`. (2认同)