侧边栏壁纸
博主头像
张种恩博主等级

一个能运维的 JPG 搬运工

  • 累计撰写 716 篇文章
  • 累计创建 62 个标签
  • 累计收到 33 条评论

目 录CONTENT

文章目录

js 中的 this 指向

张种恩
2022-06-27 / 0 评论 / 0 点赞 / 312 阅读 / 170 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-06-27,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

对象中的 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

评论区