JS高级----this指向问题和动态修改this指向


普通函数内:

       function study() {
            console.log(this);
        }

        let study1 = function() {
            console.log(this);
        }

        study(); // window 对象
        study1(); // window 对象

        let user = {
            name: 'zs',
            age: 12,
            walk: function() {
                console.log(this);
            }
        }

        user.walk(); // this指向方法在的那个对象


        user.study = study; // study函数赋值给对象的函数
        user.study(); // 对象调用study

在这里插入图片描述

得出结论:

  • 普通函数内的this指向决定于谁调用的函数,this就指向谁
  • 没有明确谁调用的时候this指向window顶级对象

箭头函数内:

        console.log(this); // window对象
        let study = function() {
            console.log(this);
        }

        let user = {
            name: 'zs',
            age: 22,
            sleep: () => {
                console.log(this);
            },

            eat: function() {
                console.log(this);
                // 对象内的函数内的箭头函数 this指向当前对象
                let eat_in = () => {
                    console.log(this);

                }
                eat_in();
            },
        }


        user.study = study;

        user.study(); // 对象调用普通函数 this指向对象
        user.sleep(); // 对象调用自身的箭头函数 this指向window对象
        user.eat(); // 对象调用对象内的普通函数  this指向对象

得出结论:

  • 箭头函数中访问的 this ,是箭头函数所在作用域的 this 变量。
  • 所以不推荐在箭头函数内使用this

修改this的指向:

Js中有三种方法可以动态指定普通函数中 this 的指向

call方法:

        function count(x, y) {
            console.log(this);
            return x + y;
        }

        let user = {
            name: 'zs',
            age: 22,
        }

        let stu = {
            name: 'ls',
            age: 22,
        }


        // this指向user对象  参数为  5  5
        let jie = count.call(user, 5, 5);
        console.log(jie);
        // this指向stu对象  参数为  3  3
        let jie2 = count.call(stu, 3, 3)
        console.log(jie2);

在这里插入图片描述

  • call 方法能够在调用函数的同时指定 this 的值

  • 使用 call 方法调用函数时,第1个参数为 this 指定的值

  • call 方法的其余参数会依次自动传入函数做为函数的参数

apply方法:

  • apply和call方法基本一致
  • apply方法有两个参数
  • 参数1为修改this指向的值
  • 参数2为一个数组 数组里面为
函数.apply(this指向,[函数内参数1,函数内参数2]);

bind方法

bind方法修改this指向会返回一个新的函数

        function count(x, y) {
            console.log(this);
            return x + y;
        }

        let user = {
            name: 'zs',
            age: 22,
        }

        let stu = {
            name: 'ls',
            age: 22,
        }


        let Count = count.bind(user);

        let jie = Count(2, 3);
        console.log(jie);

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值