> For the complete documentation index, see [llms.txt](https://1425816423.gitbook.io/my-knowledge-base/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://1425816423.gitbook.io/my-knowledge-base/qian-duan-ji-shu/shen-ru-li-jie-javascript-xi-lie/javascript-zhi-this.md).

# JavaScript之this

## JavaScript之this

`this`指向当前执行上下文的一个属性

### 普通函数中的this

**JavaScript中的`this`总是指向函数的调用者。**

这句话概括了普通函数中this的指向问题，根据不同的场景，这句话又有不同的解读。

#### 在全局对象中

全局对象中直接运行函数

```javascript
function fn(){
    console.log(this)
}
fn()  // window
```

`this`指向`window`对象，这很好理解，首先我们知道在浏览器环境下全局对象是`window`,在全局环境下执行`fn()`其实就是调用`window.fn()`，声明的`fn`其实就是`window`的一个方法，因此`this`指向它的调用者`window`。

#### 在对象的方法中

在对象的方法中，`this`指向所属对象

```javascript
let obj = {
    fn(){
        console.log(this)
    }
}
obj.fn()  // obj
```

同理，调用者是`obj`，因此this自然指向`obj`对象。

#### apply、call、bind

`apply`、`call`、`bind`这三个方法的作用是改变函数`this`的指向，因此此时`this`就是这三个方法要改变的那个对象。

```javascript
let obj = {
    a : 1
};
function fn(){
	console.log(this)
}
fn.call(obj)
// obj
```

#### 在类的构造函数中

在类的构造函数中，this指向类的实例

```javascript
class Cla {
    constructor(name){
        this.name = name
    }
}
const cla = new Cla('张三')
console.log(cla)
// {nam: "张三"}
```

#### 在闭包中

闭包中的this在严格模式下总是undefined，在非严格模式下总是指向全局对象。

```javascript
const obj = {
    fn(){
        return function(){
            console.log(this)
        }
    }
}
obj.fn()()
// window
```

### 箭头函数中的this

箭头函数本身是没有this的，因此它的this取决于上下文。

```javascript
const fn = ()=>{ console.log(this) }
fn()
// window

const obj = {
	fn: ()=>{
        console.log(this)
    }
}
obj.fn()
// window

const obj2 = {
	fn(){
        return ()=>{
            console.log(this)
        }
    }
}
obj2.fn()()
// fn
```

可以这样理解，箭头函数自身没有this，因此如果访问箭头函数的this，就会类似于作用域链查找变量一样一层一层地查找作用域中是否存在普通函数，如果有则使用该普通函数的this，如果直到全局对象里都没有找到，则此箭头函数的this就指向全局对象。

注意：箭头函数自身没有this，因此无法作为构造函数，也无法使用bind、call、apply这类改变this指向的方法。

此外

* 箭头函数无法作为generator函数，无法使用yield
* 箭头函数没有arguments，不过可以使用ES6的剩余参数解决这个问题
