1、什么是this

this个别指向的是调用它的对象,比方调用它的上下文是window对象,那就是指向window对象,如果调用它的上下文是某对象就是指向某对象……
//例如<script>    console.log(this) //window</script>//这里调用者是全局对象window,所以this指向window

<script>    var person = {            name: 'dog',            say: function () {                console.log(this);            }     }     //这里调用者是person对象,所以this指向person     person.say(); //person</script>

2、用来干嘛

this在个别状况下,是指向函数的上下文,能够解决一些作用域下的事件调用如果想要援用某对象的办法,就不必写太多反复代码,间接用this调用某对象的办法

3、怎么在代码中应用

        console.log(this); //window        var person = {            name: 'dog',            say: function () {                console.log(this); //person                console.log(this.name); //dog            }        }        person.say();        console.log(this.person.name); //dog   

4、扭转this指向

4.1引入call、bind、apply

4.1.1区别

共同点

  1. 都是函数的内置办法
  2. 都能够扭转函数执行的上下文

    注:扭转上下文能够为程序节俭内存空间,缩小不必要的内存操作通俗易懂解释扭转上下文:小张在公司有个快递要拿,刚好有事,本人拿不了,他就安顿小王拿,这里小张原本是拿快递的执行上下文,因为有事,就扭转拿快递的执行上下文,变成了小王,节约了小张的工夫,他就不必另外安顿工夫去拿快递了

    不同点

  3. call、apply是立刻执行,bind是不会立刻执行,而是返回一个回调函数,执行时须要加个()
  4. call格局为call(this.obj,arg,arg,...) , 接管一个或多个由逗号隔开的参数
  5. apply格局为apply(this.obj,[argArray]),只接管两个参数,一个是新this对象,一个是数组参数(类数组对象)
  6. bind格局为bind(this.obj,arg,arg,arg,...),接管一个或者多个有逗号隔开的参数

    4.1.2怎么用

    //call 这里能传递多个参数,也能传递参数列表     var name = 'cat'     var person = {         name: 'dog',         say: function () {             console.log(this) //window             console.log(this.name) //cat             console.log(arguments) //arguments对象             console.log(...arguments) //pig bird         },     }     //这里把this指向对象批改成window,此时this.name应该为cat     person.say.call(this, 'pig', 'bird')     person.say.call(this, ['pig', 'bird'])注:arguments对象是一个类数组对象,它具备数组长度length属性,然而又不同于数组,在参数传递上,不论对象函数是否设置形参,都能够接管用户传过来的参数,能够把参数通过数组模式的进行传递

    //apply 这里只能传递数组参数,否则会报错     var name = 'cat'     var person = {         name: 'dog',         say: function () {             console.log(this) //window             console.log(this.name) //cat             console.log(arguments); //arguments对象             console.log(...arguments);//pig bird         }     }     //这里this指向为window     person.say.apply(this, ['pig', 'bird'])     person.say.apply(this, 'pig', 'bird')//报错

//bind        var name = 'cat'        var person = {            name: 'dog',            say: function () {                console.log(this) //window                console.log(this.name) //cat                console.log(arguments);//arguments                console.log(...arguments);//pig bird            }        }        //这里this指向为window,必须加个()才算执行        person.say.bind(this, 'pig', 'bird')()        //也能够写成        var p = person.say.bind(this, 'pig', 'bird')        p()