function definitions not hoisted

青春壹個敷衍的年華 提交于 2019-11-30 08:43:11

问题


W.r.t Hoisting of fxn definitions.

if (true) {
  function foo() {
    alert(1)
  }
} else {
  function foo() {
    alert(2)
  }
}
foo()

Chrome, some 2-3 months ago - would print 2. Now, it's printing 1. Did I miss something or, did console stop hoisting on fxn's!

DEMO -- prints 1. I'm not sure where to find demo of the older browser version. Probably older v8 engine's node installation?. Current chrome version - 49


回答1:


The code you have is invalid in strict mode. Functions don't get hoisted out of blocks (or at least they shouldn't), function declarations inside blocks were completely illegal until ES6. You should write

"use strict";
var foo;
if (true) {
  foo = function() {
    alert(1)
  };
} else {
  foo = function() {
    alert(2)
  };
}
foo()

to get the desired behaviour with reproducible and expected results.

Did I miss something or, did console stop hoisting on fxn's!

Looks like V8 was updated to align with the ES6 spec. It does "hoist" them to the function/top scope, but only when the declaration is actually encountered (in your case, conditionally).




回答2:


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.



来源:https://stackoverflow.com/questions/40677540/function-definitions-not-hoisted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!