全局环境与全局函数
//this指向全局函数对象 window
console.log(this)
function fun() {
console.log(this)
}
fun()
对象
//this指向调用该方法的对象 person
let person1 = {
name: '小鹿',
todo() {
console.log(this.name)
}
}
person1.todo()
Dom事件
// 事件中的this指向触发事件的dom对象:<button></button>
const btn = document.querySelector("button")
btn.onclick = function () {
console.log(this)
}
构造函数
// new关键字做了什么:用来创建对象,将创建对象的this指向创建出来的对象f
function Fun() {
this.name = "小鹿"
}
let f = Fun()
console.log(f)
普通函数与箭头函数
let person2 = {
name: '小鹿',
todo() {
console.log(this)
// 普通函数函数外指向谁就是谁
setTimeout(function () {
console.log(this) // window
}, 1000)
// 箭头函数函数外指向谁就是谁
setTimeout(() => {
console.log(this) // person2
}, 1000)
}
}
person2.todo() //指向person2