【问题标题】:Why is the variable not being accessed [closed]为什么变量没有被访问[关闭]
【发布时间】:2018-02-21 15:09:55
【问题描述】:

似乎无法弄清楚为什么它无法访问变量“a”:

var a = function(){
    console.log('AAA');
}
(function(){
    console.log(a);
})();

【问题讨论】:

  • 为什么不是? ...
  • 您的代码在a 的值后面缺少一个分号。
  • 添加分号。您正在执行第一个函数并将第二个函数作为参数传递。然后当你尝试调用 undefined 时它会抛出一个错误,因为没有返回值。
  • JavaScript 的众多怪癖之一。不是the newline supposed to end the statement

标签: javascript scope iife


【解决方案1】:

这里的问题是你试图调用一个函数,如下undefined(),为什么?

这是正在发生的事情:

var a = function(){
    console.log('AAA');
}(...) //<- here you're calling the function `a`, but your function `a` doesn't return anything (`undefined`)

你可以通过添加分号来解决这个问题:

var a = function(){
    console.log('AAA');
}; //<- HERE!

(function(){
    console.log(a);
})();

或者,您可以将函数 a 声明为 Declaration 而不是 Expression

看看这个Question 了解更多。

function a(){
    console.log('AAA');
}

(function(){
    console.log(a);
})();

资源

【讨论】:

    【解决方案2】:

    实际上,您构建了一个 IIFE。这意味着:

     var a = function(){
        console.log('AAA');
    }
    ()
    

    实际上调用函数,并将其结果存储在a中。如果您将一个函数作为参数放入该函数调用中,则由于第一个函数不接受任何参数,因此它将无处可去。

    【讨论】:

    • 我会赞成,因为你的回答解释了问题,但它在技术上是不正确的,说and stores its result in a。由于有两个链式调用,因此从未达到分配:var a = function () { ... }(...)() 这就是问题中的 sn-p 引发错误的原因。
    【解决方案3】:

    var a = function(){
        console.log('AAA');
    };
    (function(){
        console.log(a);
        a();
    }());

    【讨论】:

    • 没有解释的答案不是答案。
    猜你喜欢
    • 2013-09-27
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2021-03-06
    • 2023-04-04
    相关资源
    最近更新 更多