如何改变函数内部this的指向

博客 动态
0 194
优雅殿下
优雅殿下 2022-04-28 18:58:32
悬赏:0 积分 收藏

如何改变函数内部 this 的指向

JS 中如何改变函数内部 this 的指向有这常用的 3 种方法

一、函数内 this 的指向

1、 this 的指向是当调用函数时确定的,调用的方式不同,this 的指向也就不同。

1.1 this 一般是指向调用者。

函数类型this 的指向
普通函数Window
定时器函数Window
立即执行函数Window
对象方法对象本身
构造函数(原型对象)实例对象

 

2、改变函数内部 this 指向

常用的 3 种方法:call()、apply()和bind()。

 

2.1 call('this 指向的对象','参数1','参数2')

  • 改变 this 指向,调用自身函数
    let obj = {    name:'Coder Yarn';};function fn(a,b){    console.log(this);    console.log(a + b);};fn.call(obj,2,5);//输出结果{name:'Coder Yarn';}7
  • 可以实现继承
    function Father(username,age,sex){    this.username = username;    this.age = age;    this.sex = sex;};function Son(username,age,sex){    Father.call(this,username,age,sex);};//实例化对象let son = new Son('Coder Yarn','22','男');console.log(son);//结果输出Coder Yarn22男

     

2.2 apply(thisArg, [argArray])

thisArg: 在 fun 函数运行时指定的 this 值。  argArray:传递的参数,必须包含在数组中

返回值就是函数的返回值,因为他就是调用函数


 

  • 改变 this 指向,调用自身的函数
  • 传的参数必须是数组(伪数组)
    //通过数学的内置方法求数组的最大值//let arr = [3,55,88,7,9];let max = Math.max.apply(Math,arr);        //this 指向 Math 实例console.log(max);//输出结果88

     

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

thisArg:在 fun() 函数运行时指定的 this 值。  arg1,arg2:传递其他参数

返回由指定的 this 值和初始化参数改造的原函数拷贝,即返回一个新的函数


 

  • 可以改变 this 的指向,但是不能调用自身的函数,只有返回的新函数可以调用自身的函数
    let obj = {    name:'Coder Yarn';};function fun(a,b){    console.log(this);    console.log(a + b);};let newfun = fun.bind(obj,2,3);newfun();//输出结果{name:'Coder Yarn';}5

     

  • bind() 的应用:函数不需要立即调用,但是想改变函数内部的 this 指向。  如:点击按钮后禁用按钮,经过 1 秒后在启用按钮
    //获取 button 按钮元素let btn = document.querySelector('button');btn.onclick = function(){    this.disabled = true; //this 指向的是 btn        //计时器    setTimeout(function(){        this.disabled = false;    //没有 bind() 方法时 this 的指向是 window ,使用 bind() 方法后 this 指向 btn    }.bind(this),1000);};//输出结果自己去实现一下吧

     

三、3 者的区别

  • call() 和 apply() 相同点:都会到用自身函数,并且该别函数内部 this 的指向;
  • call() 和 apply() 不同点:传入的参数不一样,call 是正常传参,而 apply 必须传入的是数组形式 [];
  • bind() 不会调用自身函数,但可以改变函数内部的 this 指向。
posted @ 2022-04-28 18:36 CodeYarn 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员