this 的指向問題
// 1 this 在函數中 是指向 window 的 因為 window 調用了這個函數
function fun (){
console.log(this);
}
fun(); // Window
// 2 this 在對象的指向 指向的是 obj 誰調用 this 就指向誰
var obj = {
name :"andy",
sayHi :function(){
console.log(this);
that = this;
}
}
obj.sayHi();
console.log(that === obj);
// 3 this 在構造函數中的指向是 ff 還是調用者
function Fn(){
console.log(this);
that = this;
}
var ff = new Fn();
console.log(that === ff);
- 作為純粹的函數調用 this指向全局對象window
- 作為對象的方法調用 this指向調用對象
- 作為構造函數被調用 this指向新的對象
- call,apply,bind方法調用 this指向第一個參數
- 定時器中的函數 this指向全局對象window
- ES6箭頭函數中 this指向父級的this
誰調用 this 就指向誰