js中this的指向比較繞,和其他語言可能有所不一樣,看很多資料舉的例子也很繞,這裏自己做一下記錄,方便牢記:
let a={
a:1,
check:function(){
//這裏的this指向的是該對象a的;
console.log('check:',this);
//匿名函數function() 會把this提升的指向window
let b=function(){
console.log('b:',this)
};
b();
//這裏是ec最新的箭頭函數,箭頭函數是沒有this的,這裏的this是外層傳進來的this,也就是check函數的this;
let c=()=>{
console.log('c:',this)
};
c();
}
};
function outfun(){
console.log('outfun:',this);
}
//調用函數
a.check();
outfun();
//結果
check: {a: 1, check: ƒ}
b: Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}
c: {a: 1, check: ƒ}
outfun: Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}
説明:
1.function()函數的this指向的是外層this,這個具體要看外層是什麼,如果是對象內則可能是整個對象,如果是全局函數則可能是window。
2.匿名函數this的指向是window或者undifined(typescript 嚴格模式)