简单讲解 js 中this指向问题

简单讲解 js 中this指向问题

如何判断this 倒是是哪一个对象?

看 this 在哪?
  • 1:全局 this===window

  • 2:function函数 “谁触发执向谁?”

    • 2.1 函数触发是不是 call apply bind如何是,this===参数

    • 2.2 看是不是new 触发的 是 this === new 实例的对象
      注意:看一下函数return 是否为 [数组 对象 函数],如果是 那么 this 为 retrun 值

    • 2.3 普通对象调用,在 this === 触发函数的对象

  • 3:箭头函数
    没有 this 没有 arguments
    关键看: 箭头函数卸载哪里?

    • 1: 全局 this === window
    • 2: function 函数方法中 this === function中this

代码举例

   this.aa = 123;

        function foo(params) {
            console.log('foo=========');
            console.log(this);
        }

        var obj = {
            a:foo,
            lt:()=>{
                // A window
                // B  obj
                console.log('-----------------------');
                console.log(this);
            }
        }
        obj.lt();

        var obj1 = {
            b:foo
        }
        // 函数的触发有几种方式
        // 1: 对象调用方式
        // window.foo()
        // window.obj.a()
        // // 2 new 关键字触发函数
        // var P =  new foo()
        // 3: call  aply bind 触发的函数
        // foo.apply(obj)
        // foo.call(obj1)
        // foo.bind(window)()

        // foo()
        function  bar(params) {
            // 坑:不要看代码在哪里写的
            // 看:怎么执行的
            foo()
            console.log('bar=======',this);
            var tast = ()=>{
                console.log('bar中 this ======',this);
            }

            tast()
        }
        // bar()

        // 坑: 看 写在哪里
        var tast  = ()=>{
            console.log('global========this',this);
        }
        // obj.tast = tast
        // console.log(obj);
        // obj.tast()  // 验证:箭头函数中this,不看函数是怎么触发的只看函数写在哪里
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值