2020年2月20日 星期四

Javascript this

this

不同地方有不同意義

  • 獨立的this(全域),指向他的擁有者,就是windows 物件
  • 非嚴謹模式下,在function中,是 global 物件
  • 嚴謹模式下,在function中,是 undefined
  • 在物件 event callback中, 是接收這個event的物件(實際執行callback的物件),也可解釋為擁有者
  • call(),apply()中,this是自己傳入,可以是任意物件
It has different values depending on where it is used:

In a method, this refers to the owner object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), and apply() can refer this to any object.