this指向的几种情况以及js简单实现call、apply、bind___六卿

this指向的几种情况

普通Function调用的this指向

           myFun()
           function myFun(){
               console.log(this) //window
           }

对象中方法中this指向

        let obj = {
            name:'zjq',
            age:"18",
            habby(){
                console.log(this.name,this)
            }
        }
        obj.habby() //指向obj

构造函数中的this指向

        function A(name, age){
                this.name= name;
                this.age = age;
                this.habby = function(){
                    console.log(this.name,this.age,this)  //指向实例化之后的对象
                }
            }
           let Ac = new A('zjq',18)
            Ac.habby()

箭头函数的this指向

        const A = () => {
            console.log(this)
        }
        let obj = {
            name: 'zjq',
            age: "18",
            A,
            B(){
                console.log(this,'B')
            }
        }
        console.log(obj.A())  //window
        console.log(obj.B())  //obj

普通函数我们都知道是谁调用指向谁,是在调用的时候确定的,但是箭头函数指向外层作用域,但是obj身上没有this这个变量,直到最外层window,跟着作用域往上找了
在这里插入图片描述
在这里插入图片描述

简单实现改变this指向的三种方法

call

        Function.prototype.mySelfCall = function (obj, ...arrList) {
            obj = obj ? Object(obj) : window
            let that = this; //前边的函数
            obj.fn = that;
            obj.fn(...arrList)
            delete obj.fn
        }

apply

        Function.prototype.mySelfApply = function (obj, arrList) {
            obj = obj ? Object(obj) : window
            let that = this; //前边的函数
            obj.fn = that;
            obj.fn(...arrList)
            delete obj.fn
        }

bind


        Function.prototype.mySelfBind = function (obj, ...arrList) {
            obj = obj ? Object(obj) : window
            let that = this; //前边的函数
            obj.fn = that;
            return () => { obj.fn.mySelfCall(obj, ...arrList); delete obj.fn }
        }

测试

        function A(name, age) {
            this.name = name;
            this.age = age;
            this.habby = function (...num) {
                console.log(this.name, this.age, this, ...num)  //指向实例化之后的对象
            }
        }
        let Ac = new A('zjq', 18)
        Ac.habby.mySelfCall({ name: 111, age: 222 }, 1, 2, 3, 4)
        Ac.habby.mySelfApply({ name: 333, age: 444 }, [1, 2, 3, 4, 5, 6, 7, 8])
        Ac.habby.mySelfBind({ name: 555, age: 666 }, 1, 2, 3, 4)()

在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六卿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值