您的位置:首页 > Web前端 > JavaScript

Secret of the JavaScript Ninja 学习笔记 - 3

2013-02-14 12:21 573 查看

第三章 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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息