this指向

时间:2022-07-28
本文章向大家介绍this指向,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.函数内部的this指向

这些 this 的指向,是当我们调用函数的时候确定的。调用方式的不同决定了this 的指向不同

一般指向我们的调用者.

2.改变函数内部 this 指向

JavaScript为我们专门提供了一些函数方法来帮我们更优雅的处理函数内部 this的指向问题,常用的有bind()、call()、apply()三种方法。

2.1 call方法

call()方法调用一个对象。简单理解为调用函数的方式,但是它可以改变函数的 this 指向

fun. call (thisArg, arg1, arg2, ...)

应用场景: 经常做继承.

var o = {
    name: 'andy'
}
 function fn(a, b) {
      console.log(this);
      console.log(a+b)
};
fn(1,2)// 此时的this指向的是window 运行结果为3
fn.call(o,1,2)//此时的this指向的是对象o,参数使用逗号隔开,运行结果为3

以上代码运行结果为:

2.2. apply方法

apply() 方法调用一个函数。简单理解为调用函数的方式,但是它可以改变函数的 this 指向。

fun. apply (thisArg, [argsArray])

  • thisArg :在fun函数运行时指定的this值
  • argsArray :传递的值,必须包含在数组里面
  • 返回值就是函数的返回值,因为它就是调用函数

应用场景: 经常跟数组有关系

var o = {
    name: 'andy'
}
 function fn(a, b) {
      console.log(this);
      console.log(a+b)
};
fn()// 此时的this指向的是window 运行结果为3
fn.apply(o,[1,2])//此时的this指向的是对象o,参数使用数组传递 运行结果为3

应用:

<script>
        var o = {
            name: 'andy'
        }
​
        function fn(arr) {
            console.log(this);
            console.log(arr);
        }
        fn.apply(o, ['andy']);
        // 调用函数 改变this指向
        // 参数必须是数组
        // apply的主要应用 比如借助于Math内置对象求数组最大值
        let arr = [2, 54, 7, 34, 76];
        let max = Math.max.apply(Math, arr);
        let min = Math.min.apply(Math, arr);
        console.log(max, min);
    </script>

2.3 bind方法

bind()方法不会调用函数。但是能改变函数内部this 指向

fun. bind (thisArg, arg1, arg2 ...)

  • thisArg :在fun函数运行时指定的this值
  • arg1 , arg2 :传递的其他参数
  • 返回由指定的this值和初始化参数改造的原函数拷贝(新函数)

如果只是想改变 this 指向,并且不想调用这个函数的时候,可以使用bind

应用场景:不调用函数,但是还想改变this指向

 var o = {
 name: 'andy'
 };
​
function fn(a, b) {
    console.log(this);
    console.log(a + b);
};
var f = fn.bind(o, 1, 2); //此处的f是bind返回的新函数
f();//调用新函数  this指向的是对象o 参数使用逗号隔开

bind应用:

        // 不调用函数,但是还想改变this指向
        var btn = document.querySelector('button');
        btn.addEventListener('click', function () {
            this.disabled = true;
            setTimeout(function () {
                this.disabled = false; //定时器里面的this指向的是window 
                // 使用bind方法使定时器this指向btn
            }.bind(this), 3000) //这里的this是在定时器外部,btn事件内部,所以指向的是btn
        })

2.4 call、apply、bind三者的异同

  • 共同点 : 都可以改变函数内部this指向
  • 不同点:
    • call 和 apply 会调用函数, 并且改变函数内部this指向.
    • call 和 apply传递的参数不一样,call传递参数使用逗号隔开,apply使用数组传递
    • bind 不会调用函数, 可以改变函数内部this指向.
  • 应用场景
    1. call 经常做继承.
    2. apply经常跟数组有关系. 比如借助于数学对象实现数组最大值最小值
    3. bind 不调用函数,但是还想改变this指向. 比如改变定时器内部的this指向.