What is the purpose of a self executing function i

2018-12-31 00:28发布

In javascript, when would you want to use this:

(function(){
    //Bunch of code...
})();

over this:

//Bunch of code...

16条回答
与君花间醉酒
2楼-- · 2018-12-31 00:40

Its all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of javascript code.

For example:

(function(){ 
    var foo = 3; 
    alert(foo); 
})(); 

alert(foo); 

This will first alert "3" and then throw an error on the next alert because foo is not defined.

查看更多
谁念西风独自凉
3楼-- · 2018-12-31 00:41

One difference is that the variables that you declare in the function are local, so they goes away when you exit the function and the don't conflict with other variables in other code.

查看更多
无色无味的生活
4楼-- · 2018-12-31 00:41

Self executing function are used to manage the scope of a Variable.

The scope of a variable is the region of your program in which it is defined.

A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.

As shown below, you can access the globalvariable variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.

var globalvar = "globalvar"; // this var can be accessed anywhere within the script

function scope() {
    alert(globalvar);
    localvar = "localvar" //can only be accessed within the function scope
}

scope(); 

So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.

查看更多
初与友歌
5楼-- · 2018-12-31 00:43

It looks like this question has been answered all ready, but I'll post my input anyway.

I know when I like to use self-executing functions.

var myObject = {
    childObject: new function(){
        // bunch of code
    },
    objVar1: <value>,
    objVar2: <value>
}

The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...

object: {
    childObject: {
        childObject: {<value>, <value>, <value>}
    }, 
    objVar1: <value>,
    objVar2: <value>
}

Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.

查看更多
低头抚发
6楼-- · 2018-12-31 00:44

Here's a solid example of how a self invoking anonymous function could be useful.

for( var i = 0; i < 10; i++ ) {
  setTimeout(function(){
    console.log(i)
  })
}

Output: 10, 10, 10, 10, 10...

for( var i = 0; i < 10; i++ ) {
  (function(num){
    setTimeout(function(){
      console.log(num)
    })
  })(i)
}

Output: 0, 1, 2, 3, 4...

查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 00:44

I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":

  1. Better namespace management (Avoiding Namespace Pollution -> JS Module)
  2. Closures (Simulating Private Class Members, as known from OOP)

The first one has been explained very well. For the second one, please study following example:

var MyClosureObject = (function (){
  var MyName = 'Michael Jackson RIP';
  return {
    getMyName: function () { return MyName;},
    setMyName: function (name) { MyName = name}
  }
}());

Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.

Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.

Let us try some experiments:

I can get MyName using getMyName and it works:

 console.log(MyClosureObject.getMyName()); 
 // Michael Jackson RIP

The following ingenuous approach would not work:

console.log(MyClosureObject.MyName); 
// undefined

But I can set an another name and get the expected result:

MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName()); 
// George Michael RIP

Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.

查看更多
登录 后发表回答