从jQuery中的函数外部访问变量

Ila*_*sda 1 javascript scope

请看我的exaple:

var AbcVar = "abc";

function Abc(AbcVar){
  console.log(AbcVar);
}
Run Code Online (Sandbox Code Playgroud)

这是允许函数访问的错误方法external var吗?

为什么输出 console.log undefined

Zir*_*rak 5

现在是时候见到斯科平先生了.

简单来说,范围是变量的封装(请注意,在javascript中,函数也是变量.)现在,在我刚刚编写的虚构语言中,{字符开始一个范围并}结束它,变量定义为简单相等(x = 42例如):

{                                                                    |
    x = 42;                                                          |
    {                                           |                    |
        y = "I'm in an inner scope!";           |                    |
        x == 42; //true                         |                    |
        {                                  |    |                    |
            x == 42;                       |    |                    |
            y == "I'm in an inner scope!"; |    |                    |
                                           | x, y, z are defined     |
            z = "pyramid time!";           |    |                    |
            y = y + "...not";              |    | x, y are defined   | x is defined
        }                                  |    |                    |
        y == "I'm in an inner scope!...not";    |                    |
        //z is not defined                      |                    |
        x = 4;                                  |                    |
    }                                           |                    |
    x == 4;                                                          |
    //y is undefined                                                 |
    //z is undefined                                                 |
}                                                                    |
Run Code Online (Sandbox Code Playgroud)

javascript有词法范围.简而言之,函数创建了一个新范围:

var x = 42;
(funciton () {
    x === 42;
    var y = 5;
})();
//y is undefined
Run Code Online (Sandbox Code Playgroud)

现在,还有一个可以创建变量的地方,那就是函数参数.以下两个函数的行为相同(arguments是包含传递给函数的参数的伪数组):

function parameterfull(a, b, c) {
    //do stuff with a, b, c
}

function parameterless() {
    var a = arguments[0], b = arguments[1], c = arguments[2];
    //do stuff with a, b, c
}
Run Code Online (Sandbox Code Playgroud)

如果您碰巧没有传递参数,它的值将是undefined.

现在,使用您的功能和上面的翻译:

var AbcVar = "abc";

function Abc() {
    var AbcVar = arguments[0];
    console.log(AbcVar);
}
Run Code Online (Sandbox Code Playgroud)

所以现在你明白为什么AbcVar(有时)undefined在函数内部.


tl; dr函数参数AbcVar覆盖全局变量AbcVar,因为你没有将值传递给函数,所以undefined(但只在函数内部,全局变量AbcVar保持不变.)