对象中的 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()
评论区