this 是在函數(shù)執(zhí)行的過程中自動創(chuàng)建的一個指向一個對象的內(nèi)部指針。確切的說,this并不是一個對象,而是指向一個已經(jīng)存在的對象的指針,也可以認(rèn)為是this就是存儲了某個對象的地址。
this的指向不是固定的,會根據(jù)調(diào)用的不同,而指向不同的地方。
this的綁定可以分為四種:
1.默認(rèn)綁定
2.隱式綁定
2.new 綁定
3.顯示綁定
1、默認(rèn)綁定
當(dāng)我們直接調(diào)用一個函數(shù)的時候,這個函數(shù)作用的this就是默認(rèn)綁定,
默認(rèn)綁定在window中
注意:在嚴(yán)格模式下("use strict"),默認(rèn)綁定在undefined
function foo(){
console.log(this);
}
foo(); //直接調(diào)用,默認(rèn)綁定 this 指代window
2、隱式綁定
使用 對象.方法() 這就是隱式綁定
方法中的this綁定在前面的對象中
var p = {
name : "asd",
foo : function(){
console.log(this.name)
}
}
p.foo(); //this 指代的就是p

![Uploading Paste_Image_131291.png . . .]
3.new 綁定
this 指代將來創(chuàng)建的那個對象
function Person(){
this.name = "a";
console.log(this.name);
}
var p = new Person(); //這個時候 Person中的this就是指的p
4.顯示綁定
call 、apply 只有這次調(diào)用的時候this顯示綁定
var p1 = {
name : "李四",
age : 23,
eat : function(){
console.log(this.name)
}
}
var p2 = {
name : "李五",
age : 22
}
p1.eat.call(p2); //this 指代p2
//使用call的時候,第一個參數(shù)表示p1中的this的執(zhí)行,后面的參數(shù)為向這個函數(shù)傳的值。
//注意一點:如果第一個參數(shù)是null,則this仍然是默認(rèn)的指向。
bind 會返回一個新的函數(shù),永遠(yuǎn)綁定

Paste_Image.png
5.綁定丟失問題
-
回調(diào)函數(shù)的綁定丟失問題
Paste_Image.png - 顯示 綁定傳入undefined和null的時候的問題
this就會變成默認(rèn)綁定 (window)
