this常见的指向

this的指向有哪几种?

①对象的方法---指的是谁,被哪个对象调用就是谁。

let obj = {
            a: 1,
            run() {
                console.log(this.a);
                console.log(this);
            }
        }
        // run 里面的this 就是 obj
        obj.run();

        // 在函数执行的时候确定的
        let fn = obj.run;
        //fn  全局函数--this -window
        fn();

②构造函数内部---new +构造函数

                         ---创建对象, 构造函数内部的this 就是指new的时候创建的对象。

function Movie(name) {
            this.name = name
            console.log(this);
        }
        let m1 = new Movie('奇迹');
        console.log(m1);

③事件处理函数---给谁添加的事件 ,事件处理函数中this就是谁。

    btn.onclick = function(){}  btn.addEventListenr('click',function(){}

document.onclick = function () {
          console.log(this);//document
        }

document.addEventListener('click', function () {
          console.log(this);
       })

④普通全局函数---(没有归属---看不出被谁调用---属于谁)匿名函数 ---window  

 function test() {
            // Window
            console.log(this);
        }
        test();

        setTimeout(function () {
            // Window
            console.log(this);
        }, 1000);

        let arr = [1, 2, 3];
        arr.forEach(function () {
            // Window
            console.log(this);
        })

⑤箭头函数--- 没有自己的this,跟上下文一致。

document.addEventListener('click', function () {
            console.log(this);//document

            setTimeout(() => {
                console.log(this);//document
            }, 1000);
        })

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值