我对代码做了一些评论,希望它更有意义。要理解的最重要的概念是变量提升和函数范围。JavaScript 中只有函数作用域。
x = 1;
var a = 5;
var b = 10;
var c = function (a, b, c) {
/* this `x` refers to the new `x` variable initialized below
* near the closing function `c` brace.
* It is undefined because of hoisting, and gets assigned
* a value where it was initialized below.
*/
console.log(x); // undefined
/* this `a` refers to this `a` parameter,
* because it is within this function `c` scope.
*/
console.log(a);
var f = function (a, b, c) {
/* this `b` refers to this `b` parameter,
* because it is within this function `f` scope.
*
* this `a` refers to this `a` parameter,
* because it is within this function `f` scope.
*/
b = a;
console.log(b);
/* this `b` still refers to `b` in this function `f` scope.
*
* this `c` refers to this `c` parameter,
* because it is within this function scope.
*/
b = c;
/* this is a new `x` variable because it is
* with this function `f` scope and there is no parameter `x`.
*/
var x = 5;
};
/* these `a`, `b`, and `c` variables refer to
* this function `c` parameters.
*/
f(a, b, c); // f(5, 10, 10)
console.log(b); // 9
/* this is a new `x` variable because it is
* with this function `c` scope and there is no parameter `x`.
*/
var x = 10;
};
c(8, 9, 10);
/* `a`, `b`, `c`, and `x` have not been touched,
* because the other `a`,`b`,`c` variables were parameter names,
* and other `x` variables were initialized within a different scope.
*/
console.log(b); // 10
console.log(x); // 1
JSBin 演示