this指向

this是一个使用在作用域内部的关键字,大部分使用在函数内部,很少使用在全局。

this指向不看在哪里定义,只看在哪里调用!!!

1.this在全局使用时指向顶级对象window

function fn() {
        console.log(this)
    }
    fn()  // this => window 全局调用/直接调用

 

 2.对象调用  xxx.函数名()。this指向被调用的对象

a.b.c() this 指向a.b  .前面是什么this就指向什么

var obj = {
        f:fn
    }
    obj.f // this => obj 对象调用

3.定时器调用 setTimeout/setInterval this指向window

 setTimeout(fn, 100) // this => window 定时器处理函数调用
    setInterval(onj.f, 100) // this => window 定时器处理函数调用

4.事件处理函数调用该 this指向事件源

var div = document.querySelector('div')
    div.onclick = obj.f // this => div 事件处理函数指向事件源
    div.addEventListener('click', obj.f)  // this => div 事件处理函数指向事件源

5.自执行函数调用 this指向window

看完定义来看下面这些题目!

function fn() {
        console.log(this)
    }
    setInterval(function () {
        fn() // this => window 只看在哪里调用,fn直接调用this指向window
    }, 100)
    var div = document.querySelector('div')
    div.onclick = function () {
        console.log(this) // this => div this在事件处理函数调用,this指向事件源
        fn() // this => window 只看在哪里调用,fn直接调用this指向window
    }
var obj = {
        fn: function () {
            console.log(this)
        }
    }
    obj.fn() // this => obj
    var f = obj.fn
    f() // this => window

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值