侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

js 中的 this 指向

zze
zze
2022-06-27 / 0 评论 / 0 点赞 / 443 阅读 / 1475 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

对象中的 this

// 对象中的 this 
var info = {
    name: "zze",
    getName: function () {
        console.log(this.name) // zze
        console.log(this === info) // true
    }
}

info.getName()

闭包中的 this

// 在闭包中,this 对象是在运行时基于当前执行环境绑定的,谁调用 this 指向谁
var username = "zze.outer"
var user = {
    username: "zze",
    getName: function () {
        return function () {
            console.log(this === window)
            return this.username
        }
    }
}
console.log(user.getName()()) // zze.outer

定时器中的 this

// 定时器中的 this 指向 window
var myTime = 1000
var timer = {
    myTime: 2000,
    getTime: function () {
        setTimeout(function () {
            console.log(this === window) // true
        }, 10)
    }
}

timer.getTime()

事件中的 this

// 事件中的 this
var btn = document.getElementById("btn")
btn.onclick = function (e) {
    console.log(this === e.target) // true
    console.log(this === e.currentTarget) // true
    console.log(this === btn) // true
}

btn.click()
0

评论区