What is the purpose of a self executing function in javascript?

前端 未结 19 2850
清酒与你
清酒与你 2020-11-21 04:22

In javascript, when would you want to use this:

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

over this:

//Bunch of code...
         


        
19条回答
  •  花落未央
    2020-11-21 04:57

    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: ,
        objVar2: 
    }
    

    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: {, , }
        }, 
        objVar1: ,
        objVar2: 
    }
    

    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.

提交回复
热议问题