本章將專門介紹與執行上下文建立階段直接相關的最後一個細節——this是什麼?以及它的指向究竟是什麼。express
也許你在其餘面向對象的編程語言曾經看過this
,也知道它會指向某個構造器(constructor)所創建的對象。但事實上在JavaScript裏面,this
所表明的不只僅是那個被創建的對象。編程
先來看看ECMAScript 標準規範對this 的定義:數組
「The this keyword evaluates to the value of the ThisBinding of the current execution context.」
「this 這個關鍵字表明的值爲當前執行上下文的ThisBinding。」
而後再來看看MDN 對this 的定義:瀏覽器
「In most cases, the value of this is determined by how a function is called.」
「在大多數的狀況下,this 其值取決於函數的調用方式。」
好,若是上面兩行就看得懂的話那麼就不用再往下看了,Congratulations!安全
...... 我想應該不會,至少我光看這兩行仍是不懂。app
先來看個例子吧:編程語言
var getGender = function() { return people1.gender; }; var people1 = { gender: 'female', getGender: getGender }; var people2 = { gender: 'male', getGender: getGender }; console.log(people1.getGender()); // female console.log(people2.getGender()); // female
what?怎麼people2變性了呢,這不是我想要的結果啊,爲何呢?函數
由於getGender()
返回(return)寫死了people1.gender
的關係,結果天然是'female'。ui
那麼,若是咱們把getGender
稍改一下:this
var getGender = function() { return this.gender; };
這個時候,你應該會分別獲得female
與male
兩種結果。
因此回到前面講的重點,從這個例子能夠看出,即使people1
與people2
的getGender
方法參照的都是同一個getGender function,但因爲調用的對象不一樣,因此執行的結果也會不一樣。
如今咱們知道了第一個重點,this其實是在函數被調用時發生的綁定,它指向什麼徹底取決於函數的調用方式。如何的區分this呢?
看完上面的例子,仍是有點似懂非懂吧?那接下來咱們來看看不一樣的調用方式對 this 值的影響。
狀況一:全局對象&調用普通函數
在全局環境中,this 指向全局對象,在瀏覽器中,它就是 window 對象。下面的示例中,不管是不是在嚴格模式下,this 都是指向全局對象。
var x = 1 console.log(this.x) // 1 console.log(this.x === x) // true console.log(this === window) // true
若是普通函數是在全局環境中被調用,在非嚴格模式下,普通函數中 this 也指向全局對象;若是是在嚴格模式下,this 將會是 undefined。ES5 爲了使 JavaScript 運行在更有限制性的環境而添加了嚴格模式,嚴格模式爲了消除安全隱患,禁止了 this 關鍵字指向全局對象。
var x = 1 function fn() { console.log(this); // Window 全局對象 console.log(this.x); // 1 } fn();
使用嚴格模式後:
"use strict" // 使用嚴格模式 var x = 1 function fn() { console.log(this); // undefined console.log(this.x); // 報錯 "Cannot read property 'x' of undefined",由於此時 this 是 undefined } fn();
狀況二:做爲對象方法的調用
咱們知道,在對象裏的值若是是原生值(primitive type;例如,字符串、數值、布爾值),咱們會把這個新創建的東西稱爲「屬性(property)」;若是對象裏面的值是函數(function)的話,咱們則會把這個新創建的東西稱爲「方法(method)」。
若是函數做爲對象的一個方法時,而且做爲對象的一個方法被調用時,函數中的this指向這個上一級對象。
var x = 1 var obj = { x: 2, fn: function() { console.log(this); console.log(this.x); } } obj.fn() // obj.fn()結果打印出; // Object {x: 2, fn: function} // 2 var a = obj.fn a() // a()結果打印出: // Window 全局對象 // 1
在上面的例子中,直接運行 obj.fn() ,調用該函數的上一級對象是 obj,因此 this 指向 obj,獲得 this.x 的值是 2;以後咱們將 fn 方法首先賦值給變量 a,a 運行在全局環境中,因此此時 this 指向全局對象Window,獲得 this.x 爲 1。
咱們再來看一個例子,若是函數被多個對象嵌套調用,this 會指向什麼。
var x = 1 var obj = { x: 2, y: { x: 3, fn: function() { console.log(this); // Object {x: 3, fn: function} console.log(this.x); // 3 } } } obj.y.fn();
爲何結果不是 2 呢,由於在這種狀況下記住一句話:this 始終會指向直接調用函數的上一級對象,即 y,上面例子實際執行的是下面的代碼。
var y = { x: 3, fn: function() { console.log(this); // Object {x: 3, fn: function} console.log(this.x); // 3 } } var x = 1 var obj = { x: 2, y: y } obj.y.fn();
對象能夠嵌套,函數也能夠,若是函數嵌套,this 會有變化嗎?咱們經過下面代碼來探討一下。
var obj = { y: function() { console.log(this === obj); // true console.log(this); // Object {y: function} fn(); function fn() { console.log(this === obj); // false console.log(this); // Window 全局對象 } } } obj.y();
在函數 y 中,this 指向了調用它的上一級對象 obj,這是沒有問題的。可是在嵌套函數 fn 中,this 並不指向 obj。嵌套的函數不會從調用它的函數中繼承 this,當嵌套函數做爲函數調用時,其 this 值在非嚴格模式下指向全局對象,在嚴格模式是 undefined,因此上面例子實際執行的是下面的代碼。
function fn() { console.log(this === obj); // false console.log(this); // Window 全局對象 } var obj = { y: function() { console.log(this === obj); // true console.log(this); // Object {y: function} fn(); } } obj.y();
狀況三:做爲構造函數調用
咱們可使用 new 關鍵字,經過構造函數生成一個實例對象。此時,this 便指向這個新對象。
var x = 1; function Fn() { this.x = 2; console.log(this); // Fn {x: 2} } var obj = new Fn(); // obj和Fn(..)調用中的this進行綁定 console.log(obj.x) // 2
使用new
來調用Fn(..)
時,會構造一個新對象並把它(obj)綁定到Fn(..)
調用中的this。還有值得一提的是,若是構造函數返回了非引用類型(string,number,boolean,null,undefined),this 仍然指向實例化的新對象。
var x = 1 function Fn() { this.x = 2 return { x: 3 } } var a = new Fn() console.log(a.x) // 3
由於Fn()返回(return)的是一個對象(引用類型),this 會指向這個return的對象。若是return的是一個非引用類型的值呢?
var x = 1 function Fn() { this.x = 2 return 3 } var a = new Fn() console.log(a.x) // 2
狀況四:call 和 apply 方法調用
若是你想改變 this 的指向,可使用 call 或 apply 方法。它們的第一個參數都是指定函數運行時其中的this
指向。若是第一個參數不傳(參數爲空)或者傳 null 、undefined,默認 this 指向全局對象(非嚴格模式)或 undefined(嚴格模式)。
var x = 1; var obj = { x: 2 } function fn() { console.log(this); console.log(this.x); } fn.call(obj) // Object {x: 2} // 2 fn.apply(obj) // Object {x: 2} // 2 fn.call() // Window 全局對象 // 1 fn.apply(null) // Window 全局對象 // 1 fn.call(undefined) // Window 全局對象 // 1
使用 call 和 apply 時,若是給 this 傳的不是對象,JavaScript 會使用相關構造函數將其轉化爲對象,好比傳 number 類型,會進行new Number()
操做,如傳 string 類型,會進行new String()
操做,如傳 boolean 類型,會進行new Boolean()操做。
function fn() { console.log(Object.prototype.toString.call(this)) } fn.call('love') // [object String] fn.apply(1) // [object Number] fn.call(true) // [object Boolean]
call 和 apply 的區別在於,call 的第二個及後續參數是一個參數列表,apply 的第二個參數是數組。參數列表和參數數組都將做爲函數的參數進行執行。
var x = 1 var obj = { x: 2 } function Sum(y, z) { console.log(this.x + y + z) } Sum.call(obj, 3, 4) // 9 Sum.apply(obj, [3, 4]) // 9
狀況五:bind 方法調用
調用 f.bind(someObject) 會建立一個與 f 具備相同函數體和做用域的函數,可是在這個新函數中,新函數的 this 會永久的指向 bind 傳入的第一個參數,不管這個函數是如何被調用的。
var x = 1 var obj1 = { x: 2 }; var obj2 = { x: 3 }; function fn() { console.log(this); console.log(this.x); }; var a = fn.bind(obj1); var b = a.bind(obj2); fn(); // Window 全局對象 // 1 a(); // Object {x: 2} // 2 b(); // Object {x: 2} // 2 a.call(obj2); // Object {x: 2} // 2
在上面的例子中,雖然咱們嘗試給函數 a 從新指定 this 的指向,可是它依舊指向第一次 bind 傳入的對象,即便是使用 call 或 apply 方法也不能改變這一事實,即永久的指向 bind 傳入的第一次參數。
狀況六:箭頭函數中this指向
值得一提的是,從ES6 開始新增了箭頭函數,先來看看MDN 上對箭頭函數的說明
An arrow function expression has a shorter syntax than a function expression and does notbind its ownthis
,arguments
,super
, ornew.target
. Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
這裏已經清楚了說明了,箭頭函數沒有本身的this
綁定。箭頭函數中使用的this
,實際上是直接包含它的那個函數或函數表達式中的this
。在前面狀況二中函數嵌套函數的例子中,被嵌套的函數不會繼承上層函數的 this,若是使用箭頭函數,會發生什麼變化呢?
var obj = { y: function() { console.log(this === obj); // true console.log(this); // Object {y: function} var fn = () => { console.log(this === obj); // true console.log(this); // Object {y: function} } fn(); } } obj.y()
和普通函數不同,箭頭函數中的 this 指向了 obj,這是由於它從上一層的函數中繼承了 this,你能夠理解爲箭頭函數修正了 this 的指向。因此箭頭函數的this不是調用的時候決定的,而是在定義的時候處在的對象就是它的this。
換句話說,箭頭函數的this看外層的是否有函數,若是有,外層函數的this就是內部箭頭函數的this,若是沒有,則this是window。
var obj = { y: () => { console.log(this === obj); // false console.log(this); // Window 全局對象 var fn = () => { console.log(this === obj); // false console.log(this); // Window 全局對象 } fn(); } } obj.y()
上例中,雖然存在兩個箭頭函數,其實this取決於最外層的箭頭函數,因爲obj是個對象而非函數,因此this指向爲Window全局對象。
同 bind 同樣,箭頭函數也很「頑固」,咱們沒法經過 call 和 apply 來改變 this 的指向,即傳入的第一個參數被忽略。
var x = 1 var obj = { x: 2 } var a = () => { console.log(this.x) console.log(this) } a.call(obj) // 1 // Window 全局對象 a.apply(obj) // 1 // Window 全局對象
上面的文字描述過多可能有點乾澀,那麼就看如下的這張流程圖吧,我以爲這個圖總結的很好,圖中的流程只針對於單個規則。
本篇文章介紹了 this 指向的幾種狀況,不一樣的運行環境和調用方式都會對 this 產生影響。總的來講,函數 this 的指向取決於當前調用該函數的對象,也就是執行時的對象。在這一節中,你須要掌握: