this關鍵字
this是誰和函數在哪兒定義和在哪兒執行的沒有任何關係;
如何區分this呢?
- 1.函數執行,首先看函數名前面是否有".",有的話,前面是誰this就是誰,沒有的話this就是window
//111
function fn () {
console.log(this);
}
var obj = {fn1: fn}
fn() //=>window
obj.fn1() // =>obj
//222
function sum() {
fn(); //this->window
}
sum();
//333
var oo = {
function sum() {
//this->oo
fn(); //this->window
}
}
oo.sum();
-
2.自執行函數中的this,永遠是window
-
3.給元素的某一個事件綁定方法,事件觸發的時候,執行對應的方法,方法中的this是元素本身
function fn () {
console.log(this);
}
document.getElementById('div1').onclick = fn; //fn中的this是 #div1
/////////////////////////////////////////////////////////////////////////////
var div1 = {
onclick: fn;
}
//當點擊事件觸發時,這樣就和第一點中111的代碼很相似了
div1.onclick();
document.getElementById('div1').onclick = function (){
//this->#div1
fn(); //this-> window
}
三點總體來看其實最終都是第一點,不過如果只是記憶的話,分成三點容易應付不同的場景,畢竟自己分析容易出錯。