this是函数内部的一个对象,当函数被某对象调用时,this就指向该对象
1、在构造函数中
let name='window'
function Person(name,age){
this.name=name;
this.age=age
}
this绑定在实例化的对象上
let man=new Person('hkj',21)
console.log(man.name) //hkj
直接调用,this表示window
fun();
2、在箭头函数中
var name='hkj'
function fun(){
var name="hkj1"
return ()=>{
var name='hkj2'
console.log(this.name) //hkj
return ()=>{
var name='hkj3'
console.log(this.name) //hkj
}
}
}
fun()()()
嵌套在函数中的this与调用最外层非箭头函数this
相同,最外层非箭头函数为fun(),其中的this指向window。
3、当做属性调用
var name='window'
function fun(){
var name='fun'
console.log(this.name)
}
let obj={
fun:fun,
name:'hkj'
}
obj.fun() //hkj
被当成属性调用时,函数中this指向最后一个调用函数的对象,这里指向obj
4、定时器this指向(普通函数)
var name='window'
function hello(){
this.name = 'xjy'; //setTimeout中的this并不会沿着作用域链向上找,而是指向window
setTimeout(function(){
console.log(this.name)
}, 100);
}
let obj={
name:'obj',
hello
}
obj.hello() //window
定时器普通函数内指向window。
解决办法在setTimeout里面bind(this),这样就指向obj了。
5、定时器this指向(箭头函数)
var name='window'
function hello(){
setTimeout(()=>{
console.log(this.name)
}, 100);
}
let obj={
name:'obj',
hello
}
obj.hello() //obj
定时器箭头函数内this指向调用最外层非箭头函数this
相同,即hello()由obj调用
在promise中
var p = new Promise(function(resolve, reject){
console.log(this); // window
}).then(function(){
console.log(this); // undefined
})