this 简单明了指向问题

回顾一下 JavaScript 中 this 的指向问题(非严格模式下的 this 指向)

函数的不同调用方式决定了 this 的指向不同

  1. 普通函数 this 指向 window
		function fn() {
            console.log('普通函数的this' + this);
        }
        window.fn();
  1. 对象的方法 this 指向的是对象
        var o = {
            sayHi: function() {
                console.log('对象方法的this:' + this);
            }
        }
        o.sayHi();
  1. 构造函数 this 指向 构造函数new出来的实例对象,原型对象里面的this也是指向它
        function Star() {};
        Star.prototype.sing = function() {}
        var ldh = new Star();
  1. 绑定事件函数 this 指向的是函数的调用者
		var btn = document.querySelector('button');
        btn.onclick = function() {
            console.log('绑定时间函数的this:' + this);
        };
  1. 定时器函数 this 指向的是window
        window.setTimeout(function() {
            console.log('定时器的this:' + this);
        }, 1000);
  1. 立即执行函数 this 指向的是window
        (function() {
            console.log('立即执行函数的this' + this);
        })();
要牢记一点:当前函数的 this 是在函数被调用执行的时候才确定的。
  • 全局对象中的 this 指向它本身。
  • 函数中的 this 在一个函数的执行上下文中,this 由该函数的调用者提供,由调用函数的方式来决定其指向。
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值