I just can't understand why the the a1 = function ?
and where is my value 1 that was passed to the fn(),
whether it was overrwrited by var a ?
问题看起来像是由相同的名称(var 和 function)引起的!
function fn(a) {
console.log("a1 = " + a);
var a = 2;
function a() { }
console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2
function fnx(ax) {
console.log("a1 = " + ax);
var ax = 2;
function b() { }
console.log("a2 = " + ax);
}
fnx(1);
// a1 = 1
// a2 = 2
/* it equal to the final version */
function fn(a) {
var a;
a = function() { }
// function hoisting > variable hoisting
console.log("a1 = " + a);
a = 2;
console.log("a2 = " + a);
}
fn(1);
// a1 = function a() { }
// a2 = 2
最佳答案
I just can't understand why the the a1 = function ?
函数声明是:
- 提升到它们出现的函数的顶部
- 在局部变量出现的函数范围内声明一个局部变量(与函数同名)(这不相关,因为参数定义也会这样做)
- 将自己指定为该变量的值
and where is my value 1 that was passed to the fn(),
被函数声明覆盖
whether it was overrwrited by var a ?
var
被忽略,因为已经有一个名为 a
的局部变量。
赋值会覆盖两个 console.log
语句之间的函数。
您的代码实际上与以下内容相同:
function fn(a) {
a = function a() { };
console.log("a1 = " + a);
a = 2;
console.log("a2 = " + a);
}
fn(1);
关于javascript - 如何深入理解Javascript的var作用域和闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198746/