1.单独使用this
console.log(this,'全局this')
严格和非严格模式打印结果都为window
2.普通函数的使用(用于访问当前方法所属的对象)
2.1直接调用
function a(){
console.log(this)
}
a()
打印的结果还是window,但是在严格模式下是undefined。
2.2对象中方法
let obj1={
a(){
console.log(this,this===obj1)
},
b:1,
c:'hello'
}
obj1.a()
打印结果:this就是方法所属的对象obj1,可以看到this和obj1是全等的
2.3事件函数,以onclick为例
document.getElementById('sub').onclick=function(){
console.log(this,this===document.getElementById('sub'))
}
打印结果:this指向button节点,也就是在事件函数中,this指向执行函数的节点
2.4Window 对象方法的使用,以setTimeout()为例
function a(){
console.log(this)
}
setTimeout(a,100)
打印结果:this指向window,因为setTimeout方法是windows下的方法
2.5new 关键字调用函数,this 指代new出来的新的
let newthis//使用newthis是为了判断用new调用函数后的this指向,是否指向新的
function a(){
console.log(this)
newthis=this
}
let newa=new a()
console.log(newa===newthis)
打印结果:
3.箭头函数
箭头函数没有自己的this指向,它会向外层查找,指向外层中最近的一层指向的this。
直接全局调用:
'use strict'
const a=()=>{
console.log(this)
}
a()
在严格模式和非严格模式都是window。
对象中的箭头函数:
let obj1={
a:()=>{
console.log(this)
},
b:1,
c:'hello'
}
obj1.a()
箭头函数a的父级是obj1,obj1的this指向window,因此打印结果为window。