之前在一个微信群里有人提出一个问题,为什么下面的代码中,最后一行的输出a是1
vara=0;if(true){console.log(1,a)a=1console.log(2,a)functiona(){}console.log(3,a)a=2console.log('里面',a,typeofa)}console.log('外面',a,typeofa)
这应该是因为function声明变量导致的,不过我们不应该在满足某种条件的时候才去声明函数,因为我们可能会有一个报错
Function statements should not be placed in blocks. Use a function expression or move the statement to the top of the outer function.
根据jslint的解释,
This error is raised to highlightcode that may not work as you expect it to. In most environments Your code will run without error, but maybe not in the way you expect. In some environments it could cause afatal syntax error.
Function declarations (or "function statements" as they are misleadingly called in the JSLint error message) are hoisted to the top of the scope in which they appear, as described by Declaration Binding Instantiation (ES5 §10.5). Therefore, it is not possible to conditionally declare a function with a function statement.
简单来说,即便代码可以运行,但可能不会像你所预期的那样去执行。由于function声明的变量会被提升最上层的作用域,尽管不满足if的条件, 函数还是会被声明。
functiona(){}if(true){...}
这也是为什么上面的代码中第一个console.log里的a会是一个函数,如果一定有这样的需求,可以考虑用赋值的方式
varexample;if(true){example=function(){console.log('hello');}}