对象内部的this指向问题

1.

const obj2 = {
    fn: () => {
        console.log(this);
    }
}
obj2.fn(); // window 


上面代码中箭头函数没有自己的this,向上找this对象(在对象大括号中没有作用域?),所以最终指向window。

2.

const obj2 = {
    fn: function() {
        console.log(this); // obj2
    }
};
obj2.fn();


上述代码fn函数被obj2对象调用,this指向obj2

二、对象中的函数返回一个函数
1.

const obj2 = {
    fn: function() {
        console.log("1", this);
        return function() {
            console.log("2", this);
        }
    }
}
obj2.fn()(); // 1 obj2 2 window


上述代码fn返回一个函数这个函数没有明显被谁调用,那就是被window调用了。

2.

const obj2 = {
   fn: function() {
       console.log("1", this);
       return () => {
           console.log("2", this);
       }
   }
}
obj2.fn()(); // 1 obj2 2 obj2


上述代码fn返回一个箭头函数,虽然没有明确调用者,但是这里箭头函数可能涉及到往上一层作用域中搜索this,上一层作用域就是fn函数的作用域,因为被obj2调用,因此this指向obj2。

三、函数中有立即执行函数
1.

const obj2 = {
   fn: function() {
       console.log("1", this);
       (function() {
           console.log("2", this);
       })();
       return () => {
           console.log("3", this);
       }
   }
}
obj2.fn()(); // 1 obj2 2 window 3 obj2

这里,执行了一个立即执行函数,没有明确的调用者,this指向window。

2.

const obj2 = {
   fn: function() {
       console.log("1", this);
       (() => {
           console.log("2", this);
       })();
       return () => {
           console.log("3", this);
       }
   }
}
obj2.fn()(); // 1 obj2 2 obj2 3 obj2


这里跟上面例子基本相同,只不过这里立即执行函数是箭头函数,箭头函数向上一层作用域中查找this,于是找到了fn中的this,

四、有定时器的情况
1.

const obj2 = {
    fn: function() {
        console.log("1", this);
        (() => {
            console.log("2", this);
        })();
        return () => {
            console.log("3", this);
            setTimeout(() => {
                console.log("4", this);
            }, 0);
        }
    }
}
obj2.fn()(); // 1 obj2 2 obj2 3 obj2 4 obj2

这里的定时器回调函数是箭头函数,还是涉及到向上一级作用域搜索this。

2.

const obj2 = {
    fn: function() {
        console.log("1", this);
        (() => {
            console.log("2", this);
        })();
        return () => {
            console.log("3", this);
            setTimeout(function() {
                console.log("4", this);
            }, 0);
        }
    }
}
obj2.fn()(); // 1 obj2 2 obj2 3 obj2 4 window

这里的定时器回调函数没有明确调用者,this指向window。

补充关于箭头函数中arguments问题
在箭头函数中,和this相似arguments也指向上一层函数中的arguments。

function f1(x, y) {
    return (z) => {
        console.log(arguments);
    }
}

const tempFn = f1(1, 2);
tempFn(3);
/*
[Arguments] { '0': 1, '1': 2 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值