function definitions not hoisted

后端 未结 2 2035
没有蜡笔的小新
没有蜡笔的小新 2020-12-18 07:30

W.r.t Hoisting of fxn definitions.

2条回答
  •  一向
    一向 (楼主)
    2020-12-18 07:44

    You should avoid using conditionally created functions.

    For example, assume the following code:

    if (false){
     function foo(){
      console.log(1)
     }
    }
    foo()
    

    Firefox will not hoist the function and this will result in ReferenceError: foo is not defined. Chrome, however, hoists the function nonetheless and prints 1. So obviously you have deal with different browser behaviour. Therefore, do not do things like that at all (or use function expressions if you really want to).

    Also see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

    Functions can be conditionally declared, that is, a function statement can be nested within an if statement. Most browsers other than Mozilla will treat such conditional declarations as an unconditional declaration and create the function whether the condition is true or not, see this article for an overview. Therefore they should not be used, for conditional creation use function expressions.

    Especially look at the linked article which somewhat explains the issue you are seeing. So Chrome seems to have changed something in that regard. But again, do not use conditionally created functions.

    And note that, as FREEZE commented, you should use 'use strict'; which would not allow such code but throws an exception instead.

提交回复
热议问题