1.2.javacript的this
Javascript的this指向哪個物件, 具體指向哪個物件是在運行時基於函數的執行環境動態綁定,而非函數被宣告時的環境.
使用上基本可分為三種情形:
1.Object中的this:
被作為物件的屬性呼叫時
this指向該物件
example code: http://codepen.io/JenHsuan/pen/QpvrLN?editors=1012
2.Function中的this:
1.作為普通函數呼叫
this指向全域物件. 在瀏覽器中便是指向windows物件
example code: http://codepen.io/JenHsuan/pen/QpvrLN?editors=1012
2.建構子呼叫: 可細分三種情形
1.建構子沒有顯式地回傳值 -> this會指向原函數(使用建構子建立的物件)
2.建構子有顯式地回傳值, 回傳值為物件-> this會指向回傳值
3.建構子有顯式地回傳值, 回傳值不是物件-> this會指向原函數(使用建構子建立的物件)
example code: http://codepen.io/JenHsuan/pen/QpvrLN?editors=1012
3.使用function.prototype.call或function.prototype.apply呼叫
可以動態改變this所指向的物件
this指向傳入的物件
example code: http://codepen.io/JenHsuan/pen/QpvrLN?editors=1012
Last updated
Was this helpful?