码迷,mamicode.com
首页 > 其他好文 > 详细

函数提升

时间:2017-08-16 15:22:31      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:log   表达   cas   assigned   conf   ems   uri   port   nbsp   

在写JS代码的时候,有两种写法,一种是函数表达式,另外一种是函数声明方式。我们需要重点注意的是,只有函数声明形式才能被提升。

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 there are 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("this won‘t run!");
    }
    function bar() { // function declaration, given the name ‘bar‘
        alert("this will run!");
    }
}
test();

 

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

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

函数提升

标签:log   表达   cas   assigned   conf   ems   uri   port   nbsp   

原文地址:http://www.cnblogs.com/lulin1/p/7373137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!