1. 普通函数
function fn() {
console.log('xxx')
}
this 指向 window
2. 对象方法
let o = {
sayHi:function() {
console.log('xxx')
}
}
o.sayHi()
this 指向的是对象 o
3. 构造函数
function Star(uname,age,sex) {
this.name = uname
this.age = age
this sex = sex
this.sing = function(sang) {
console.log(sang)
}
}
let ldh = new Star('刘德华', 60, 男)
ldh.sing('冰雨')
this 指向 ldh 这个实例对象
4. 绑定时间函数
let btn = document.querySelector('button')
btn.onclick = function() {
console.log('绑定事件函数的this' + this)
}
this 指向的是函数的调用者
5. 定时器函数
window.setTimeout(function() {
console.log('定时器的this' + this)
},1000)
this 指向 window
6. 立即执行函数
(function() {
console.log('立即执行函数的this' + this)
})()
this 指向 window