javascript - 如何深入理解Javascript的var作用域和闭包?

标签 javascript scope closures

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 ?

函数声明是:

  1. 提升到它们出现的函数的顶部
  2. 在局部变量出现的函数范围内声明一个局部变量(与函数同名)(这不相关,因为参数定义也会这样做)
  3. 将自己指定为该变量的值

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/

相关文章:

python - 为什么子函数不继承 Python 中的作用域?

rust - 什么时候应该使用函数指针而不是闭包?

javascript - jQuery视差滚动卡住

javascript - chrome.experimental.socket API速成类(class)?

javascript - 避免在 HTML 中公开 LinkedIn API key

javascript - 如何计算多行的总和?

r - 带有来自另一个函数输入的额外参数的函数

python - 列表推导式中定义的变量是否会泄漏到封闭范围中?

swift - 如何在函数中抛出一个闭包?

swift - 为什么我不能返回一个从声明为 "-> () -> some View"的 Swift 函数返回 View 的闭包?