this 在 js 中的指向性问题

this 的指向问题


 // 1 this 在函数中 是指向 window 的 因为 window 调用了这个函数
        function fun (){
            console.log(this);
        }
        fun(); // Window
        // 2 this 在对象的指向 指向的是 obj 谁调用 this 就指向谁
        var obj = {
            name :"andy",
            sayHi :function(){
                console.log(this);
                that = this;
            }
        }
        obj.sayHi();
        console.log(that === obj);

        // 3 this 在构造函数中的指向是 ff 还是调用者
        function Fn(){
            console.log(this);
            that = this;
        }
        var ff = new Fn();
        console.log(that === ff);


  • 作为纯粹的函数调用 this指向全局对象window
  • 作为对象的方法调用 this指向调用对象
  • 作为构造函数被调用 this指向新的对象
  • call,apply,bind方法调用 this指向第一个参数
  • 定时器中的函数 this指向全局对象window
  • ES6箭头函数中 this指向父级的this

谁调用 this 就指向谁

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值