原则是谁调用,就指向谁
1:common function,
this指向Window
function fn(){ console.log(this) } fn()
//this-->Window
2:Object function,
this指向方法所属对象
var o={ fn:function(){ console.log(this) } }
fn() //this-->o
3:construct,this指向实例对象
function Star(name,age){ this.name=name; this.age=age; }
Star.prototype.sing=function(){
console.log(this)
}
let star=new Star('tom',18)
star.sing();
this-->star实例对象
4:定时器,this指向Window
setTimeout( function(){ console.log(this) },1000 )
//this-->Window
5:bind event function,
this指向绑定事件元素
document.body.onclick=function(){ console.log(this) }
//this-->element
6:立即执行函数Immediately-Invoked Function Expression 即IIFE,
this指向Window
(function(){ console.log(this) })()
//this-->Window
二、严格模式"strict"
1:common function,
this指向undefined
'use strict' function fn()} console.log(this) }
fn() //this-->undefined
2:定时器,严格模式下this还是指向Window
'use strict' setTimeout( function(){ console.log(this) },1000 )
//this-->Window
class A { constructor() { } handleClick() { console.log(this) } } var a = new A() a.handleClick() // this-->A实例 let b= a.handleClick b() // this-->undefined, 因为b是一个引用,不是实例调用,类中的方法开启了局部严格模式
三、React 函件组件中的this
this->undefined
因为babel翻译的时候使用了严格模式