javascript变量预解析与函数声明提前
ringa_lee
ringa_lee 2017-04-10 14:29:58
[JavaScript讨论组]

这里同时出现了函数声明提前,和变量的预解析,但是不管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_Cheatsheet
function: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 function
expressed: 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());
ringa_lee
ringa_lee

ringa_lee

全部回复(5)
黄舟

由于js有声明提前,你的代码等同于下面。

  function bar() {
        var foo;
        function foo() {};
        return foo;
        //以下不会被执行
        foo = 10;        
        foo = 11;
    }
    console.log(typeof bar());
黄舟
function bar() {
  var foo;
  return foo;
  function foo() {};
  foo = 11;
}

function foo() {}
函数声明会在执行前被解析 存在于当前上下文的任意一个地方 typeof(foo) 已经为 Function
var foo = 11 只会提前声明出变量 foo

PHPz

函数声明会在任何表达式被解析和求值之前先被解析和求值,即使你的声明在代码的最后一行,它也会在同作用域内第一个表达式之前被解析/求值

怪我咯

因为你这种情况出现时, 都已function为准, 不管顺序如何.

PHP中文网

在ECMAScript中,有一个叫做执行上下文(Execution Contexts)的概念,他在理论上规定了函数在执行时的执行顺序[具体则是由浏览器引擎来实现,不过chrome的v8引擎和firefox的 xxx-spider引擎在实现上会有一些细节的差异。],这里涉及到的2个执行顺序的规则如下:

  1. 使用function声明的函数会最先被编译,因此在相同作用域中,我们总能直接使用function声明的函数;

  2. 使用var声明的变量和函数表达式会被自动提升到作用域的顶部,这种现象叫做hoisting

于是这个问题就很好解释了。
想要深入了解执行上下文,可点击这里
你也可以继续阅读汤姆大叔的这系列文章,非常有价值.深入理解javascript系列

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号