JavaScript高级--- (4)改变函数内部this指向的方法

x33g5p2x  于2021-09-24 转载在 JavaScript  
字(1.1k)|赞(0)|评价(0)|浏览(271)

一、一般函数内部this指向

如下图:

二、改变函数内部this指向的方法

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

1、call()方法

使用方法:
fun.call(thisArg, arg1, arg2, …)

  • thisArg:在 fun 函数运行时指定的 this 值
  • arg1,arg2:传递的其他参数
  • 返回值就是函数的返回值,因为它就是调用函数
  • 因此当我们想改变 this 指向,同时想调用这个函数的时候,可以使用 call,比如继承(见下例)
// 实现继承
        function father(name, age) {
            this.name = name;
            this.age = age;
        }

        function Son(name, age) {
            father.call(this, name, age)
        }

        var ldh = new Son('ldh', 18);
        console.log(ldh);

2、apply()方法

使用方法:
fun.apply(thisArg, [argsArray])

  • thisArg:在fun函数运行时指定的 this 值
  • argsArray:传递的值,必须包含在数组里面
  • 返回值就是函数的返回值,因为它就是调用函数
  • 因此 apply 主要跟数组有关系,比如使用 Math.max() 求数组的最大值(见下例)
// 利用数学内置对象求最大值
        var arr = [1, 2, 3, 4, 8, 5, 6];
        var num = Math.max.apply(Math, arr);
        console.log(num);  // 8

3、bind()方法

使用方法:
fun.bind(thisArg, arg1, arg2, …)

  • thisArg:在 fun 函数运行时指定的 this 值
  • arg1,arg2:传递的其他参数
  • 返回由指定的 this 值和初始化参数改造的原函数拷贝
  • 因此当我们只是想改变 this 指向,并且不想调用这个函数的时候,可以使用 bind

例如:我们希望实现以下功能,点击按钮后三秒内禁用,三秒后恢复。

先定义一个按钮

<button>dianji</button>

然后获取按钮,分析需求

// 函数不希望立即调用,同时希望更改this指向
        var btn = document.querySelector("button");
        btn.onclick = function() {
            this.disabled = true;
            setTimeout(function() {
                this.disabled = false; //this指向window,用bind更改
            }.bind(this), 3000);
        }

4、总结

下一篇:JavaScript高级—(5)ES5严格模式

相关文章