# this **Repository Path**: chengll000/this ## Basic Information - **Project Name**: this - **Description**: 简单总结ES6箭头函数和普通函数this的指向 - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-04-17 - **Last Updated**: 2021-08-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### this指向总结 ### 一、全局执行 #### 1. 非严格模式 浏览器下this指向window ```js console.log(this); // window ``` #### 2. 严格模式 严格模式下this指向undefined ```js "use strict"; console.log(this); // undefined ``` ### 二、作为对象方法执行 1.调用方式为对象.方法()时,该方法中的this指向这个对象。即谁调用指向谁。 ```js var obj = { name:'aaa', hello3(){ console.log('我是hello3 this:',this); // obj } } obj.hello3(); // obj ``` 2.若将对象的方法赋值给一个变量,然后使用变量调用该方法时,this指向window。 ```js var obj = { name:'aaa', hello3(){ console.log('我是hello3 this:',this); // obj } } var func = obj.hello3; func(); // window ``` ### 三、定时器内部执行 定时器`setTimeOut`和`setInterVal`内部的`this`都指向`window` ```js setTimeout(()=>{ console.log(this); // window },2000) ``` ### 四、构造函数内部执行 构造函数的调用要使用new,所以,构造函数中的this,指向该构造函数实例出的对象p。 ```js function Person(name){ this.name = name console.log(this) } var p1 = new Person('yunxi'); // Person ``` ### 五、箭头函数 箭头函数的this是在定义时根据上下文函数决定的。 1.当箭头函数的上下文没有函数环境时,即直接调用时,`this`指向`window/undefined` ```js var obj = { a: 100, hello5:()=>{ console.log(this.a) } } obj.hello5(); // undefined ``` 2.当箭头函数有上下文函数环境时,`this`指向上下文函数的`this`。(因为是`obj2`调用的`hello6`,所以箭头函数的`this`,也就是`hello6`的`this`)。 ```js var obj2 = { a: 100, hello6:function(){ var a = 200; setTimeOut(()=>{ console.log(this.a) },2000) } } obj2.hello6(); // 100 ``` ### 六、call、apply、bind 使用call、apply、bind可以修改this的指向(箭头函数不可以) 1.call的用法 (1)call的第一个参数就是this,若第一个参数传的是null,则不会改变this指向。 (2)call 可以传多个参数 ```js function fn(){ console.log(this) } var obj = { a: 100 } fn.call(obj); // {a:100} fn.call(obj,[1,2],true,{},false) ``` 2.apply用法 apply只接受2个参数, (1)第一个参数就是this,若第一个参数传的是null,则不会改变this指向。 (2)第二个参数必须是数组 ```js function fn(){ console.log(this) } var obj = { a: 100 } fn.apply(obj); // {a:100} fn.apply(obj,[1,2,4]) ``` 2.bind用法 (1)bind绑定this时不会立即执行。 (2)bind的第一个参数就是this,若第一个参数传的是null,则不会改变this指向。 (3)bind 可以传多个参数。 ```js function fn(){ console.log(this) } var obj = { a: 100 } fn.bind(obj)(); // {a:100} ``` #### 总结: 相同点: bind、call、apply都可以改变this的指向,其中接受的第一个参数就是this。若第一个参数传的null,都不会改变this的指向。 不同点: 1.bind不会立即执行,而apply和call会立即执行。 2.apply和call的区别是,apply只能接受两个参数并且第二个参数必须是数组,而call可以接受很多参数并且不限制类型。