这里同时出现了函数声明提前,和变量的预解析,但是不管(var foo = 11;放哪里,都返回function这里表述有误为什么SF中Markdown的~~删除线~~不能用...),是什么原因
function bar() {
return foo;
foo = 10;
function foo() {};
var foo = 11;
}
console.log(typeof bar());//function 为什么不是number
网上查的资料:
http://www.bootcss.com/article/variable-and-function-hoisting-in-javascript/
解析器将当前作用域内声明的所有变量和函数都会放到作用域的开始处
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheetfunction:Three forms with different scope behavior:
(为什么有三种...)declared: as a statement at the parent function top-level
behaves like a var binding that gets initialized to that function initialization**"hoists" to the very top of the parent function, above vars**
函数声明提前到当前作用域最顶端,在var之上,但还是不懂:最顶端,那不会被后来的var给覆盖么statement:as a statement in a child block
behaves like a var binding that gets initialized to that function
does not hoist to the top of the parent functionexpressed: inside an expression bound in the expression only
然后现在,问题变成了:为什么var foo无论放在function foo...前面还是后面,都返回function
function bar() {
var foo;
function foo() {};
return foo;
}
console.log(typeof bar());
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
由于js有声明提前,你的代码等同于下面。
function foo() {}函数声明会在执行前被解析 存在于当前上下文的任意一个地方
typeof(foo)已经为Function而
var foo = 11只会提前声明出变量foo因为你这种情况出现时, 都已
function为准, 不管顺序如何.在ECMAScript中,有一个叫做执行上下文(Execution Contexts)的概念,他在理论上规定了函数在执行时的执行顺序[具体则是由浏览器引擎来实现,不过chrome的v8引擎和firefox的 xxx-spider引擎在实现上会有一些细节的差异。],这里涉及到的2个执行顺序的规则如下:
使用function声明的函数会最先被编译,因此在相同作用域中,我们总能直接使用function声明的函数;
使用var声明的变量和函数表达式会被自动提升到作用域的顶部,这种现象叫做
hoisting。于是这个问题就很好解释了。
想要深入了解执行上下文,可点击这里
你也可以继续阅读汤姆大叔的这系列文章,非常有价值.深入理解javascript系列