> ## Content Index
> Fetch the complete content index at: https://blog.hacking.pub/llms.txt
> Use this file to discover other available public pages before exploring further.

# js 变量作用域
- URL: https://blog.hacking.pub/2017/02/13/js-bian-liang-zuo-yong-yu/
- Published: 2017-02-13T08:41:56.000Z
- Updated: 2017-02-13T08:47:51.000Z
- Author: chainhelen
- Tags: js, javascript, nodejs, 作用域, 趣题

#### 问题

今天有人发了一个网站，[问题来源](http://dmitry.baranovskiy.com/post/91403200?winzoom=1&ref=blog.hacking.pub)。

---

**一**

```
if (!("a" in window)) {
    var a = 1;
}
console.log(a);

```

按照这种思路就可解，变量声明会被提前，也就是说上面的代码等价于下面代码

```
var a;
if (!("a" in window)) {  
    a = 1;
}
console.log(a);
//所以a未定义，打印为undefined

```

---

**二**

```
var a = 1,
    b = function a(x) {
        x && a(--x);
    };
console.log(a);

```

同样代码，声明提前，等价如下代码

```
var a;
function a(x) {
    x && a(--x);
};
a = 1;
console.log(a);
//打印为 1

```

---

**三**

```
function a(x) {
    return x * 2;
}
var a;
console.log(a);

```

同样变

```
var a;
function a(x) {
    return x * 2;
}
console.log(a);
//打印函数a的内容

```

---

**四**

```
function b(x, y, a) {
    arguments[2] = 10;
    console.log(a);
}
b(1, 2, 3);

```

arguments就是输入的参数数组，argument是引用  
上面的代码可以按照下面这么理解

```
function b() {
    arguments[2] = 10;

    //每次用x, y, a的时候，都是重新去arguments数组里面去取
    var x = arguments[0];
    var y = arguments[1];
    var a = arguments[2];
    console.log(a);
}
b(1, 2, 3);
//打印为 10

```

---

**五**

```
function a() {
    alert(this);
}
a.call(null);
//打印为 Windows对象

```

大坑，记住下面一句话

```
apply/call传null或者undefined,指向的window对象，this指向全局对象

```

---

**未经授权，禁止转载**  
**by chainhelen**