在javascript中this的指向一直是前端同事的心頭病,也同時是各面試題的首選,現在我們就來總結一下js中this的指向。首先需要了解一下幾個概念:
1:全局變量默認掛載在window對象下
2:一般情況下this指向它的調用者
3:es6的箭頭函數中,this指向創建者,并非調用者
4:通過call、apply、bind可以改改變this的指向
下面我們具體分析一下
1:在函數調用時
(非嚴格模式)
const func = function () { console.log(this); const func2 = function () { console.log(this); }; func2(); //Window }; func(); //Window(嚴格模式)
'use strict' const func = function () { console.log(this); const func2 = function () { console.log(this); }; func2(); //undefined }; func(); //undefined結合第四和第一兩條規則:func這個函數是全局的,默認掛載在window對象下,this指向它的調用者即window,所以輸出window對象,但是在嚴格模式下,this不允許指向全局變量window,所以輸出為undefined(func2在函數直接調用時默認指向了全局window,其實這屬于javascript設計上的缺陷,正確的設計方式是內部函數的this 應該綁定到其外層函數對應的對象上,為了規避這一設計缺陷,聰明的 JavaScript 程序員想出了變量替代的方法,約定俗成,該變量一般被命名為 that。這種方式在接下來會講到)。
2:作為對象方法
const user = { userName: '小張', age: 18, selfIntroduction: function () { const str = '我的名字是:' + this.userName + ",年齡是:" + this.age; console.log(str); const loop = function () { console.log('我的名字是:' + this.userName + ",年齡是:" + this.age); }; loop(); //我的名字是:undefined,年齡是:undefined } }; user.selfIntroduction(); //我的名字是:小張,年齡是:18按照咱的第一條規則,this指向他的調用者,selfIntroduction()方法的調用者是user,所以在selfIntroduction()方法內部this指向了他的父對象即user,而loop方法輸出的為undefined的原因就是我在上面所說的javascript的設計缺陷了,在這種情況下,我們通常選擇在selfIntroduction()方法里將this緩存下來。
const user = { userName: '小張', age: 18, selfIntroduction: function () { const str = '我的名字是:' + this.userName + ",年齡是:" + this.age; console.log(str); const that=this; const loop = function () { console.log('我的名字是:' + that.userName + ",年齡是:" + that.age); }; loop(); //我的名字是:小張,年齡是:18 } }; user.selfIntroduction(); //我的名字是:小張,年齡是:18此時loop的this指向就理想了。
const user={ userName:'小張', age:18, selfIntroduction:function(){ const str='我的名字是:'+this.userName+",年齡是:"+this.age; console.log(str); } }; const other =user.selfIntroduction; other(); //我的名字是:undefined,年齡是:undefined const data={ userName:'小李', age:19, }; data.selfIntroduction=user.selfIntroduction; data.selfIntroduction(); //我的名字是:小李,年齡是:19
新聞熱點
疑難解答
圖片精選