this是一个使用在作用域内部的关键字,大部分使用在函数内部,很少使用在全局。
this指向不看在哪里定义,只看在哪里调用!!!
1.this在全局使用时指向顶级对象window
function fn() {
console.log(this)
}
fn() // this => window 全局调用/直接调用
2.对象调用 xxx.函数名()。this指向被调用的对象
a.b.c() this 指向a.b .前面是什么this就指向什么
var obj = {
f:fn
}
obj.f // this => obj 对象调用
3.定时器调用 setTimeout/setInterval this指向window
setTimeout(fn, 100) // this => window 定时器处理函数调用
setInterval(onj.f, 100) // this => window 定时器处理函数调用
4.事件处理函数调用该 this指向事件源
var div = document.querySelector('div')
div.onclick = obj.f // this => div 事件处理函数指向事件源
div.addEventListener('click', obj.f) // this => div 事件处理函数指向事件源
5.自执行函数调用 this指向window
看完定义来看下面这些题目!
function fn() {
console.log(this)
}
setInterval(function () {
fn() // this => window 只看在哪里调用,fn直接调用this指向window
}, 100)
var div = document.querySelector('div')
div.onclick = function () {
console.log(this) // this => div this在事件处理函数调用,this指向事件源
fn() // this => window 只看在哪里调用,fn直接调用this指向window
}
var obj = {
fn: function () {
console.log(this)
}
}
obj.fn() // this => obj
var f = obj.fn
f() // this => window