开发者

Javascript parse/evaluation order?

开发者 https://www.devze.com 2022-12-28 21:41 出处:网络
This is probably a nub question, but I don\'t understand why this works: <script type=\"text/javascript\">

This is probably a nub question, but I don't understand why this works:

<script type="text/javascript">
    alert(foo);
    function foo() { }
</script>

This alerts "function foo() { }", but I expected开发者_如何学Python the alert to be evaluated before the function foo was defined. Can someone explain what I don't understand about parse/evaluation order or point me to a resource that does?


JavaScript, like PHP, tracks top-level function declarations before the code runs. However, you can bypass the auto-function by using assignments:

var a = function a() { }


A must read about the types of function definitions in JavaScript.

Named Function Expressions Demystified


Function declarations are hoisted to the top, and therefore declared first and foremost.

You can change this behavior by assigning them to a variable like so

var a = function() {
   // do it
};

This assigns the variable a to an anonymous function.

0

精彩评论

暂无评论...
验证码 换一张
取 消