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.
精彩评论