Do you know why this code doesn't give ReferenceError? What is the name of feature?

enter image description here

收藏 0 分享浏览 1298
4年前
跟帖
前端乱炖
4年前

刚才群里还在讨论这个问题吧,貌似是 预编译的名词。

大概意思就是var x;在预编译的时候会提前。

沙发
张小俊128
4年前
@前端乱炖 是类似与function hoist么
板凳
张小俊128
4年前

Javascript中当一个函数没有显示的指明return语句时,它会默认返回undefined。还有如小炖君所说,会有”预编译”的问题,可能类似于JavaScript中的function hoist。

地板
_煜森
4年前

Function declarations and variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there. This means that code like this:

function foo(){
  bar();
  var x = 1;
}

is actually interpreted like this:

function foo(){
   var x;
   bar();
   x = 1;
}

It turns out that it doesn’t matter whether the line that contains the declaration would ever be executed. The following two functions are equivalent:

function foo() {
    if (false) {
        var x = 1;
    }
    return;
    var y = 1;
}
function foo() {
    var x, y;
    if (false) {
        x = 1;
    }
    return;
    y = 1;
}

Notice that the assignment portion of the declarations were not hoisted. Only the name is hoisted. This is not the case with function declarations, where the entire function body will be hoisted as well.

原文链接: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

4 楼
说几句
广告位 点击查看投放指南

我的收藏