this 是 JavaScript 語言的一個關鍵字。
它是函數運行時,在函數體內部自動生成的一個對象,只能在函數體內部使用。
function test() { this.x = 1; }
上面代碼中,函數 test 運行時,內部會自動有一個 this 對象可以使用。
一、this 的值是什么
函數的不同使用場合,this 有不同的值。
總的來說,this 就是函數運行時所在的環境對象。
二、this 的使用場景
1、作為一般函數執行
2、作為對象屬性執行
3、作為構造函數執行
4、通過 call、apply、bind 調用
三、this 的判斷
1. 作為一般函數執行時,this 指代全局對象
function test(){ this.x = 1; alert(this.x); } test(); // 1
2. 作為對象屬性執行時,this 指代上級對象
function test(){ alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); // 1
3. 作為構造函數調用時,this 指代 new 出的對象
var x = 2; function test(){ this.x = 1; } var o = new test(); alert(x); // 2 alert(o.x); // 1
對於 new 的方式來說,this 被永遠綁定在了 o 上面
4. call、apply、bind 調用時,this 指代第一個參數
let a = {} let fn = function () { console.log(this) } fn.bind().bind(a)()
上述代碼中,不管我們給函數 bind 幾次,fn 中的 this 永遠由第一次 bind 決定,所以結果永遠是 window
四、總結