简体   繁体   English

我们应该或不应该在Javascript中的main函数内部函数声明后使用分号?

[英]should or shouldn't we use semicolon after a function declaration inside a main function in Javascript?

I've come across multiple examples and I'm getting confused about placing semicolon after declaring a function where it acts as a function inside function as shown in the below example 我遇到过多个例子,我对于在声明一个函数后放置分号感到困惑,它在函数内部充当函数,如下例所示

var myFunction = function() {
   var value = "parentValue";   

   function otherFunction() {
      var value = "childValue";
      console.log("Value is : "+value);
   }

   otherFunction();
}

myFunction();

ie placing the semicolon in the end of the otherFunction () declaration. 即将分号放在otherFunction ()声明的末尾。 If I keep ; 如果我保持; or not it's working. 或不是它的工作。 So which is the best practice? 哪个是最好的做法?

Function declarations are no statements. 函数声明不是语句。 They are not terminated by a semicolon, you should not use any. 它们不是以分号结尾的,你不应该使用任何分号。

If you put a semicolon there, it's parsed as an empty statement after the declaration. 如果你在那里放了一个分号,它会在声明后被解析为一个空语句。

However, not all function definitions are statements. 但是,并非所有函数定义都是语句。 myFunction is a variable that is assigned a function expression, and assignments are expression (or variable declaration) statements that are (should be) terminated by a semicolon. myFunction是一个赋值函数表达式的变量,赋值是(应该)以分号结束的表达式(或变量声明)语句。

function otherFunction() {
    …
} // <-- no semicolon after declaration

var myFunction = function() {
    …
}; // <-- semicolon after assignment

See also var functionName = function() {} vs function functionName() {} for more differences. 另请参阅var functionName = function(){} vs function functionName(){}以获取更多差异。

Note that the assignment of the anonymous function to myFunction needs a semi colon, no other statement in this scenario is required... 请注意,为myFunction分配匿名函数需要一个半冒号,在这种情况下不需要其他语句......

   var myFunction = function() 
   {
       var value = "parentValue"; // declaring a var so use semicolon

       function otherFunction() 
       {
          var value = "childValue"; // declaring a var so use semicolon
          console.log("Value is : "+value)
       } // is not being assigned to anything so no need for semicolon

       otherFunction()

    }; // declaring a var so use semicolon

    myFunction()

And to give an idea how this would work with the module pattern... 并且想一想这将如何与模块模式一起工作......

var Module = (function(){

    var value = "parentValue";

    function _myFunction()
    {
        _otherFunction()
    } 

    function _otherFunction() 
    {
        var value = "childValue";
        console.log("Value is : "+value)
    }

    return{

        myFunction: _myFunction()
    }; // with semicolon

})(); // with semicolon

Module.myFunction;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM