如何通过var scope&深入了解Javascript关闭? [英] How to understand Javascript in deep with var scope & closure?
本文介绍了如何通过var scope&深入了解Javascript关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是不明白为什么 a1 =函数吗?
,我的价值在哪里 1 传递给 fn(),
and where is my value 1 that was passed to the fn(),
是否被 var a ?
该问题看起来是由相同的名称引起的(var& function)!
the problem look like caused by the same names( 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
推荐答案
我只是不明白为什么a1 =函数?
I just can't understand why the the a1 = function ?
函数声明为:
- 悬挂在它们出现的函数顶部
- 在它们出现的函数范围内声明一个局部变量(与该函数同名)(这无关紧要,因为参数定义也这样做)
- 将自己分配为该变量的值
以及传递给fn()的我的值1在哪里,
and where is my value 1 that was passed to the fn(),
被函数声明覆盖
是否被var a覆盖?
whether it was overrwrited by var a ?
var
被忽略,因为已经有一个名为 a
的局部变量。
The var
is ignored because there is already a local variable named a
.
赋值将覆盖两个 console.log
语句之间的函数。
The assignment overwrites the function between the two console.log
statements.
您的代码实际上与以下代码相同:
Your code is effectively the same as:
function fn(a) {
a = function a() { };
console.log("a1 = " + a);
a = 2;
console.log("a2 = " + a);
}
fn(1);
这篇关于如何通过var scope&深入了解Javascript关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文