javascript函数声明提前的一个例子

来源:互联网 发布:tensorflow 安装 编辑:程序博客网 时间:2024/06/10 02:34

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. But remember that thereare two normal ways to declare functions. Consider the following JavaScript:

function test() {

        foo(); //TypeError "foo is not a function"

        bar(); //"this will run!"

        var foo =function () { // function expression assigned to local variable 'foo'

               alert("thiswon't run!");

        }

        functionbar() { // function declaration, given the name 'bar'

               alert("thiswill run!");

        }

}

test();

In this case, only the function declaration has its body hoisted to thetop. The name ‘foo’ is hoisted, but the body is left behind, to be assignedduring execution.

That covers the basics of hoisting, which is not as complex or confusingas it seems. Of course, this being JavaScript, there is a little morecomplexity in certain special cases.

 

0 0
原创粉丝点击