第三章 Functions are fundamental
3.2 Declarations
Function literal ::=
function [funcName]
(<parameters>
) { <statements>
}
All functions have a property named name.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
/**
* Declares a named function. The name is available throughout the current scope
* and is implicitly added as a property of window
*/
function isNimble() { return true; }
/**
* Creates an anonymous function that's assigned to the variable canFly. The variable
* is a window property and the name property of the function is empty
*/
var canFly = function() { return true; }
/**
* Creates an anonymous function referenced by property of window
*/
window.isDeadly = function() { return true; }
/**
* Defines an inner function inside the outer function That inner()
* is able to be referenced before and after its declaration and that no global name is created for inner()
*/
function outer() {
inner();
function inner() { print "inner"; }
inner();
window.inner === undefined;
}
outer();
/**
* The variable that we assign a function to has nothing to do with its name. That's
* controlled by what we actually name the function in its literal
*/
window.wieldSword = function swingWord() { return true; };
window.wieldSword.name === "swingWord";
</script>
</head>
<body>
</body>
</html>
Scoping and functions
In JavaScript, scopes are declared by functions, and not by blocks.
if (window) {
var x = 123;
}
alert(x);
a few nuances:
- Variable declarations are in scope from their point of declaration to the end of the function within which they're declared, regardless of block nesting.
- Named functions are in scope within the entire function within which they're declared, regardless of block nesting.
- For the purposes of declaration scopes, the global context acts like one big function encompassing the code on the page.